<?php
class Pay{
    #region 通过订单号查询充值线路后按线路来执行查询
    public static function publicOrderQuery($paras){
        global $db;
        global $utility;
        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'orderid',
            'realprice|F|0',
        );

        $paras = $utility->get_url_args($paras, $url_args);
        $db_prefix = \Config\Sys::$dbprefix;

        $sql = "SELECT r.paywayid,w.payclass,r.lineid,r.amount FROM `{$db_prefix}users_recharge` r,`{$db_prefix}pay_way` w WHERE w.id=r.paywayid AND r.rechargeid='{$paras['orderid']}' LIMIT 1";
        $paywayclass = $db->row($sql);

        $orderQueryFunc = $paywayclass['payclass'].'OrderQuery';

        $sql = "SELECT * FROM `{$db_prefix}rechargeline` WHERE `id`={$paywayclass['lineid']} LIMIT 1";
        $payline = $db->row($sql);
        $payline['amount'] = $paywayclass['amount'];

        return self::$orderQueryFunc($paras['orderid'], $payline, $paras);
    }
    #endregion

    #region 支付宝和微信的查询订单并确认充值
    /**
     * @param $orderid string 订单号
     * @param $buyer_pay_amount string 买家实付金额
     */
    private static function ConfirmUserRecharge($orderid,$buyer_pay_amount)
    {
        global $db;
        global $redis;
        global $utility;
        $db_prefix = \Config\Sys::$dbprefix;
        $rechargediscdcoin = 0;//充值优惠
        $result = array(
            'state' => 404,
            'msgid' => 10079, // 已确认充值
        );
        $nowtime = time();
        # 找出对应订单的信息、用户及订单状态等
        $sql = "SELECT r.`id`,r.`uid`,r.`amount`,u.`agentlevel`,u.`userlevel`,l.`give`,u.`parentid`,u.`usertype`,r.`state` from `{$db_prefix}users_recharge` r,`{$db_prefix}users` u,`{$db_prefix}rechargeline` l WHERE u.`uid`=r.`uid` AND l.`id`=r.`lineid` AND r.`rechargeid`='{$orderid}' LIMIT 1";

        //print_r($sql);

        $recharge = $db->row($sql);

        if(!$recharge){
            $result['state'] = 404;
            $result['msgid'] = 10000;
            return $result;
        }

        if($recharge && intval($recharge['state']) == 1){
            $result['state'] = 200;
            $result['msgid'] = 10079;
            $result['amount'] = $recharge['amount'];
            $result['discd'] = floatval($recharge['amount']) * floatval($recharge['give']) / 100;
            return $result;
        }
        $dbym = date('Ym');
        # 查询本订单是否已经有记帐变
        $sql = "SELECT COUNT(1) AS __TOTAL FROM ".\Config\Sys::$dbprefix."coinlog_".$dbym." WHERE ex2='{$orderid}' LIMIT 1";
        //print_r($sql);
        $confirmcount = $db->row($sql);

        //print_r($confirmcount);

        $confirmcount = $confirmcount['__TOTAL'];

        if($confirmcount > 0){
            return $result;
        }

        $db->beginTrans();

        # 更新充值状态及具体充值金额
        $db->update($db_prefix.'users_recharge')->cols(array(
            'state' => 1,
            'rechargetime' => $nowtime,
            'rechargeamount' => $buyer_pay_amount,
            'info' => '充值成功',
        ))->where('id='.$recharge['id'])->query();


        # 2018-07-06 按充值汇总的金额大于等于50（后台定义）时激活上级的推荐资金
        # $sql = "SELECT SUM(`rechargeamount`) AS _TOTAL FROM `".$db_prefix."users_recharge` WHERE `uid`=".$recharge['uid']."AND `state`=1";
        # $recharge_total = $db->row($sql);
        # $recharge_total = $recharge_total['_TOTAL'];

        # 查看当前用户的代理等级及充值折扣
        //$agentupdategiveway = intval($utility->getSystemParams('agentupdategiveway'));
        if( $recharge['usertype'] == 2) {
            # 找出代理线
            $agent = $utility->getAgentLevelForLid(array('lid' => $recharge['agentlevel']));
            $rechargediscd = $agent['rechargediscd'];
            $rechargediscdcoin = $rechargediscd * $buyer_pay_amount / 100;
            $rechargediscdcoin = $utility->formatCoin($rechargediscdcoin);
            if (floatval($rechargediscdcoin) > 0) {
                $utility->setCoin(array(
                    'uid' => $recharge['uid'],
                    'gameid' => 0,
                    'coin' => $rechargediscdcoin,
                    'liqtype' => 26,
                    'ex1' => $recharge['id'],
                    'ex2' => $orderid,
                    'ex3' => $buyer_pay_amount . '×' . $rechargediscd . '%',
                ));
            }
        }

        # 当前VIP等级充值折返 - 后续将升级 VIP 等级，但本次还是按当前的等级赠送
        //$vipupdategiveway = intval($utility->getSystemParams('vipupdategiveway'));
        if( $recharge['usertype'] != 2) {
            # 找出用户VIP等级,如果有充值赠送的将赠送给玩家
            $sql = "SELECT `rechargediscd` FROM `" . \Config\Sys::$dbprefix . "userlevel` WHERE `lid`=" . $recharge['userlevel'] . " LIMIT 1";
            $vipdb = $db->row($sql);
            if ($vipdb && floatval($vipdb['rechargediscd']) > 0) {
                $rechargediscdcoin = $buyer_pay_amount * $vipdb['rechargediscd'] / 100;
                if ($rechargediscdcoin > 0) {
                    $utility->setCoin(array(
                        'uid' => $recharge['uid'],
                        'gameid' => 0,
                        'coin' => $rechargediscdcoin,
                        'liqtype' => 26,
                        'ex1' => $recharge['id'],
                        'ex2' => $orderid,
                        'ex3' => $buyer_pay_amount . '×' . $vipdb['rechargediscd'] . '%',
                    ));
                }
            }
        }

        # 当前线路是否有赠送
        if(floatval($recharge['give'])>0)
        {
            $giveCoin = $buyer_pay_amount * $recharge['give'] / 100;
            if($giveCoin > 0) {
                $utility->setCoin(array(
                    'uid' => $recharge['uid'],
                    'gameid' => 0,
                    'coin' => $giveCoin,
                    'liqtype' => 26,
                    'ex1' => $recharge['id'],
                    'ex2' => $orderid,
                    'ex3' => $buyer_pay_amount . '×' . $recharge['give'] . '%',
                ));
            }
        }


        $sql = "SELECT `uno`,`nickname`,`recharge` FROM ".\Config\Sys::$dbprefix."users WHERE `uid`=".$recharge['uid']." LIMIT 1";
        //echo $sql;
        $rc = $db->row($sql);
        $rechargeCount = $rc['recharge'];
        # 充值总额要加上本次的充值金额，用户的充值总额是要在setCoin执行后才会更新
        $rechargeSum = floatval($rc['recharge']) + floatval($buyer_pay_amount);

        $sumrechargecoin = $utility->getSystemParams('sumrechargecoin');

        # 当用户充值的金额达到指定的赠送额度后，给当前用户和推荐人加入赠送的金额
        if($rechargeSum >= floatval($sumrechargecoin)){
            # 当前用户的存款满赠送时，要给推荐人加入赠送金额
            $sql = "SELECT `uid`,`uno`,`coin`,`score`,`parentid`,`parents`,`tel`,`agentlevel`,`userlevel`,`usertype` FROM `".\Config\Sys::$dbprefix."users` WHERE `uid`='".$recharge['parentid']."' AND `usertype`>0 LIMIT 1";
            $parent = $db->row($sql);
            if($parent) {
                # 查找是否已经赠送,如果有赠送即不再赠送，没有就赠送过去
                $sql = "SELECT COUNT(1) AS _TOTAL FROM `".\Config\Sys::$dbprefix."recharge_give` WHERE `uid`={$parent['uid']} AND `fromuid`={$recharge['uid']} LIMIT 1";
                $isgive = $db->row($sql);
                if($isgive['_TOTAL'] == 0) {
                    $sql = 'SELECT `pushusergive` FROM `' . \Config\Sys::$dbprefix . 'agentlevel` WHERE `lid`=' . $parent['agentlevel'] . ' LIMIT 1';
                    $agent = $db->row($sql);
                    if ($parent['usertype'] == 2 && $agent['pushusergive'] > 0) {
                        $utility->setCoin(array(
                                'uid' => $parent['uid'],
                                'coin' => $agent['pushusergive'],
                                'liqtype' => 25,
                                'ex1' => $recharge['uid'],
                                'ex2' => '',
                                'ex3' => $rc['nickname'].'('.$rc['uno'].')存满' . $sumrechargecoin . '赠送',
                            )
                        );

                        # 有赠送的把它记录到赠送库里
                        $sql = "INSERT INTO `".\Config\Sys::$dbprefix."recharge_give` (uid,fromuid,coin,actiontimes,liqtype) VALUES(";
                        $sql .= $parent['uid'].",".$recharge['uid'].",".$agent['pushusergive'].",".time().",1)";
                        $db->query($sql);
                    }
                }
            }
        }
        if(empty($rechargeCount)) {
            # 首次成功充值成功的金额大于firstrechargecoin时赠送firstrechargegive
            $firstrechargecoin = $utility->getSystemParams('firstrechargecoin');
            $firstrechargegive = $utility->getSystemParams('firstrechargegive');

            if (floatval($firstrechargegive) > 0 AND $buyer_pay_amount >= floatval($firstrechargecoin)) {
                //$firstrechargegivecoin = $buyer_pay_amount * $firstrechargegive / 100;
                $firstrechargegivecoin = $firstrechargegive;
                $utility->setCoin(array(
                    'uid' => $recharge['uid'],
                    'gameid' => 0,
                    'coin' => $firstrechargegivecoin,
                    'liqtype' => 32,
                    'ex1' => $recharge['id'],
                    'ex2' => $orderid,
                    'ex3' => $buyer_pay_amount . '×' . $firstrechargegive . '%',
                ));
            }
        }

        # 记录帐变
        $utility->setCoin(array(
            'uid' => $recharge['uid'],
            'gameid' => 0,
            'coin' => $buyer_pay_amount,
            'liqtype' => 21,
            'ex1' => $recharge['id'],
            'ex2' => $orderid,
        ));

        # 更新用户的VIP等级
        $utility->updateUserVip($recharge['uid']);

        $db->commitTrans();
        return array(
            'state' => 200,
            'msgid' => 10079,
            'amount' => $buyer_pay_amount, // 实收的金额
            'discd' => $rechargediscdcoin, // 给玩家的充值折扣（优惠）
        );
    }
    #endregion

    # region 取出所有可以用指定充值通道
    /**
     * 取出所有可以用指定充值通道
     * @param $args
     */
    public static function getPayWay($args)
    {
        global $db;
        global $redis;
        global $utility;

        $db_prefix = \Config\Sys::$dbprefix;

        $url_args = array("w");
        $get_args = $utility->get_url_args($args, $url_args);

        //只能是web,app,mobile
        $mastWayName = array('web','mobile','app');
        if(in_array($get_args['w'],$mastWayName)) {
            $redis_key = \Config\Sys::$redisKey['PAYWAYS'] . $get_args['w'];
            if ($redis->exists($redis_key)) {
                $data = $utility->redisGet($redis_key);
            } else {
                $sql = "SELECT `id`,`title`,`payclass`,REPLACE(`logo`,'/upload/','') as logo,`memo`,`rechargemoney` FROM `{$db_prefix}pay_way` WHERE FIND_IN_SET('{$get_args['w']}',`payfrom`) AND `state`=1 ORDER by `sort` DESC";

                $data = $db->query($sql);
                if ($data) {
                    foreach ( $data as $k=>$v ){
                        if( $v['rechargemoney'] ){
                            $data[$k]['rechargemoney'] = explode(',',$v['rechargemoney']);
                        }else{
                            $data[$k]['rechargemoney'] = [];
                        }
                        if( strstr($v['payclass'],'wechat') ){
                            $data[$k]['paytype'] = 'wechat';
                        }elseif( strstr($v['payclass'],'alipay') ){
                            $data[$k]['paytype'] = 'alipay';
                        }else{
                            $data[$k]['paytype'] = 'other';
                        }
                    }
                    $utility->redisSet($redis_key, $data);
                } else {
                    $data = array();
                }
            }
        }else{
            $data = array();
        }
        return $data;
    }
    # endregion

    # region 充值线路选择并执行对应的充值过程
    public static function getRechangeLine($args)
    {
        global $db;
        global $utility;

        $db_prefix = \Config\Sys::$dbprefix;

        $url_args = array(
            "payid", //通道类名称
            "payfrom",//平台标识
            "uno",//用户uno
            "amount",//充值金额
            "remoteip", //ip
            'cmd',
            'token'
        );
        $paras = $utility->get_url_args($args, $url_args);
        $data = array('state'=>404, 'msgid'=>404);
        if(empty($paras['uno']) || empty($paras['amount']))
        {
            return array(
                'state' => 404,
                'msgid' => 404,
                'data' => array(
                    'state' => 404,
                    'msgid' => 404,
                ),
            );
        }
        $minrecharge = $utility->getSystemParams('minrecharge');
        $maxrecharge = $utility->getSystemParams('maxrecharge');

        if($minrecharge > $paras['amount'] || $paras['amount'] > $maxrecharge)
        {
            return array(
                'state' => 200,
                'msgid' => 10082,
                'data' => array(
                    'state' => 404,
                    'msgid' => 10082,
                    'min' => $minrecharge,
                    'max' => $maxrecharge,
                ),
            );
        }
        $user = $utility->exitsToKen($paras['token'],$paras['cmd']);
        if( $user['state'] != 200 ){
            $result['state'] = $user['state'];
            $result['cmd'] = $paras['cmd'];
            $result['msgid'] = $user['msgid'];
            return [
                'state' => $result['state'],
                'data'  => [
                    'state' => $result['state'],
                    'msgid' => $user['msgid'],
                ]
            ];
        }
        # 先确定是哪个玩家的充值，只要有Token就指定到相应的玩家帐号
        $sql = "SELECT `uid`,`uno`,`nickname`,`parentid`,`coin`,`usertype`,`userlevel`,`agentlevel`,`tel`,`usertype` FROM `{$db_prefix}users` WHERE `uno`='{$user['uno']}' LIMIT 1";
        $user = $db->row($sql);
        if(!$user)
        {
            $data = array(
                'state'=>404,
                'msgid'=>10002,
                'data' => array(
                    'state' => 404,
                    'msgid' => 10002,
                ),
            );
            return $data;
        }
        if($user['usertype']==0)
        {
            $data = array(
                'state'=>200,
                'msgid'=>10085,
                'data' => array(
                    'state' => 404,
                    'msgid' => 10085,
                ),
            );
            return $data;
        }
        # 计算充值金额，后期要加上VIP几充值打几折


        //只能是web,app,mobile
        $mastWayName = array('web','mobile','app');

        //print_r($mastWayName);
        if(in_array($paras['payfrom'],$mastWayName)) {

            //echo $paras['payfrom'];

            # 取出对应的充值通道
            $sql = "SELECT `id`,`payclass`,`rechargemoney` FROM `{$db_prefix}pay_way` WHERE `id`='{$paras['payid']}' AND FIND_IN_SET('{$paras['payfrom']}',`payfrom`) AND `state`=1";
            $payway = $db->row($sql);
            //print_r($payway);
            if(!$payway)
            {
                $data = array('state'=>404, 'msgid'=>10045);
                return [
                    'state' => 404,
                    'data'  => $data
                ];
            }
            #取充值线路
            $sql = "SELECT * FROM `{$db_prefix}rechargeline` WHERE `paywayid`={$payway['id']} AND `state`=1";
            $paylines = $db->query($sql);
            if(!$paylines)
            {
                $data = array('state'=>404, 'msgid'=>10045);
                return [
                    'state' => 404,
                    'data'  => $data
                ];
            }
            #根据充值渠道，判断可支付的金额
            if( $payway['rechargemoney'] || $payway['rechargemoney'] != 0 ){ //0允许所有的充值金额
                $allowRechargeMoney = explode(',',$payway['rechargemoney']);
                $istrueRecharge = false;
                if( is_array($allowRechargeMoney) ){
                    foreach ( $allowRechargeMoney as $value ){
                        if( $value == $paras['amount'] ){
                            $istrueRecharge = true;
                            break;
                        }
                    }
                }
                if( $istrueRecharge == false ){
                    $data = array('state'=>404, 'msgid'=>10116,'msg'=>"允许充值金额{$payway['rechargemoney']}");
                    return [
                        'state' => 404,
                        'data'  => $data
                    ];
                }
            }
            # 随机取一条对应的充值线路
            $randid = array_rand($paylines, 1);
            $payline = $paylines[$randid];
            # 回调中用到的域名，如果有指定creurl的就用creurl没有的就用系统指定的官网域名
            $creUrl = (empty($payline['creurl']) ? $utility->getSystemParams('apiurl') : $payline['creurl']);

            # 同步通知
            $syncUrl = $utility->getSystemParams('weburl').'/mime.html';

            # 取用户折扣
            $paras['paycoin'] = $paras['amount'];
            # 指定充值时间
            $paras['nowtime'] = time();
            # 记录充值数据
            $paras['uid'] = $user['uid'];
            $paras['uno'] = $user['uno'];
            $paras['usertype'] = $user['usertype'];
            $paras['usercoin'] = $user['coin'];
            $paras['lineclass'] = $payline['lineclass'];
            $paras['transfername'] = '-';
            if($payway['id'] == 2) $paras['transfername'] = '';
            $paras['rechargeid'] = $utility->insertRechargeToDb($paras, $payline);
            # 订单标题
            $paras['subject'] = '【'.$utility->getSystemParams('website_name').'】订单支付';
            # 订单详情
            $paras['body'] = '【'.$utility->getSystemParams('website_name').'】订单支付';
            # 同步通知地址
            $paras['synchro_url'] = $syncUrl;
            # 异步通知地址
            $paras['notify_url'] = $creUrl . '/pay/notify';
            # 按充值支付方式来执行对应的过程
            $result = array(
                'state' => 200,
            );
            //echo $payway['payclass'];
            switch ($payway['payclass'])
            {
                case "transfer": // 银联转帐
                    $result['data'] = self::transfer($paras, $payline);
                    break;
                case "alipay": //支付宝快捷支付
                    $result['data'] = self::alipay($paras, $payline);
                    break;
                case "wxpayapp": //微信APP支付
                    $result['data'] = self::wxpayapp($paras, $payline);
                    break;
                case "weixinh5": //微信H5调起APP支付
                    $result['data'] = self::weixinh5($paras, $payline);
                    break;
                case "xinyihepay":
                    $result['data'] = self::xinyihepay($paras, $payline);
                    break;
                case 'ddbpay':
                    $result['data'] = self::ddbpay($paras, $payline);
                    break;
                case 'paysapialipay'://PaysApi支付宝
                    $result['data'] = self::paysapialipay($paras, $payline);
                    break;
                case 'paysapiwxpay'://PaysApi微信
                    $result['data'] = self::paysapiwxpay($paras, $payline);
                    break;
                case 'qrcodepay'://扫码支付
                    $result['data'] = self::qrcodepay($paras, $payline);
                    break;
                case 'qwjwxcodepay'://千万家微信扫码支付,
                    $paras['notify_url'] = $creUrl . '/pay/qwjnotify';
                    $result['data'] = self::qwjwxcodepay($paras,$payline);
                    break;
                case 'qwjwxh5pay':
                    $paras['notify_url'] = $creUrl . '/pay/qwjnotify';
                    $result['data'] = self::qwjwxh5pay($paras,$payline);
                    break;
                case 'qwjalipaycodepay':
                    $paras['notify_url'] = $creUrl . '/pay/qwjnotify';
                    $result['data'] = self::qwjalipaycodepay($paras,$payline);
                    break;
                case 'qwjtransfercodepay':
                    $paras['notify_url'] = $creUrl . '/pay/qwjnotify';
                    $result['data'] = self::qwjtransfercodepay($paras,$payline);
                    break;
                case 'mfalipaypay': //密付支付宝扫码
                    $paras['notify_url'] = $creUrl . '/pay/mfnotify';
                    $result['data'] = self::mfalipaypay($paras,$payline);
                    break;
                case 'mfh5alipaypay': //密付支付宝h5
                    $paras['notify_url'] = $creUrl . '/pay/mfnotify';
                    $result['data'] = self::mfh5alipaypay($paras,$payline);
                    break;
                case 'mfunionpay': //密付银联扫码
                    $paras['notify_url'] = $creUrl . '/pay/mfnotify';
                    $result['data'] = self::mfunionpay($paras,$payline);
                    break;
                case 'mfh5unionpay': //密付银联h5
                    $paras['notify_url'] = $creUrl . '/pay/mfnotify';
                    $result['data'] = self::mfh5unionpay($paras,$payline);
                    break;
                case 'mfkuaijiepay': //快捷支付
                    $paras['notify_url'] = $creUrl . '/pay/mfnotify';
                    $result['data'] = self::mfkuaijiepay($paras,$payline);
                    break;
                case 'mfwechatpay': //微信扫码
                    $paras['notify_url'] = $creUrl . '/pay/mfnotify';
                    $result['data'] = self::mfwechatpay($paras,$payline);
                    break;
                case 'mfqqpay': //qq
                    $paras['notify_url'] = $creUrl . '/pay/mfnotify';
                    $result['data'] = self::mfqqpay($paras,$payline);
                    break;
                case 'mfh5wechatpay': //微信h5
                    $paras['notify_url'] = $creUrl . '/pay/mfnotify';
                    $result['data'] = self::mfh5wechatpay($paras,$payline);
                    break;
                case 'mfh5qqpay': //qqh5
                    $paras['notify_url'] = $creUrl . '/pay/mfnotify';
                    $result['data'] = self::mfh5qqpay($paras,$payline);
                    break;
                case 'mfunionqrpay': //云闪付
                    $paras['notify_url'] = $creUrl . '/pay/mfnotify';
                    $result['data'] = self::mfunionqrpay($paras,$payline);
                    break;
                case 'sdh5alipaypay': //三多支付宝h5
                    $paras['notify_url'] = $creUrl . '/pay/sdnotify';
                    $result['data'] = self::sdh5alipaypay($paras,$payline);
                    break;
                case 'sdalipaypay': //三多支付宝扫码
                    $paras['notify_url'] = $creUrl . '/pay/sdnotify';
                    $result['data'] = self::sdalipaypay($paras,$payline);
                    break;
                case 'sdh5wechatpay': //三多微信h5
                    $paras['notify_url'] = $creUrl . '/pay/sdnotify';
                    $result['data'] = self::sdh5wechatpay($paras,$payline);
                    break;
                case 'sdwechatpay': //三多微信扫码
                    $paras['notify_url'] = $creUrl . '/pay/sdnotify';
                    $result['data'] = self::sdwechatpay($paras,$payline);
                    break;
                case 'cytunionfastpay': //诚易通前台快捷
                    $paras['notify_url'] = $creUrl . '/pay/cytnotify';
                    $result['data'] = self::cytunionfastpay($paras,$payline);
                    break;
                case 'cytalipaypay'://诚易通前台快捷支付宝扫码
                    $paras['notify_url'] = $creUrl . '/pay/cytnotify';
                    $result['data'] = self::cytalipaypay($paras,$payline);
                    break;
                case 'cytwechatpay'://诚易通前台快捷支付宝扫码
                    $paras['notify_url'] = $creUrl . '/pay/cytnotify';
                    $result['data'] = self::cytwechatpay($paras,$payline);
                    break;
                case 'dbalipaypay': //豆瓣支付
                    $paras['notify_url'] = $creUrl . '/pay/notify';
                    $result['data'] = self::dbalipaypay($paras,$payline);
                    break;
                case 'lmalipaypay': //老马支付宝支付
                    $paras['notify_url'] = $creUrl . '/pay/notify';
                    $result['data'] = self::lmalipaypay($paras,$payline);
                    break;
                case 'lmunionpay'://老马云闪付支付
                    $paras['notify_url'] = $creUrl . '/pay/notify';
                    $result['data'] = self::lmunionpay($paras,$payline);
                    break;
                case 'lmwechatpay'://老马微信支付
                    $paras['notify_url'] = $creUrl . '/pay/notify';
                    $result['data'] = self::lmwechatpay($paras,$payline);
                    break;
                case 'yxbh5alipaypay'://银信宝支付宝h5
                    $paras['notify_url'] = $creUrl . '/pay/notify';
                    $result['data'] = self::yxbh5alipaypay($paras,$payline);
                    break;
                case 'yxbalipaypay'://银信宝支付宝
                    $paras['notify_url'] = $creUrl . '/pay/notify';
                    $result['data'] = self::yxbalipaypay($paras,$payline);
                    break;
                case 'yxbh5wechatpay'://银信宝微信h5
                    $paras['notify_url'] = $creUrl . '/pay/notify';
                    $result['data'] = self::yxbh5wechatpay($paras,$payline);
                    break;
                case 'yxbwechatpay'://银信宝微信
                    $paras['notify_url'] = $creUrl . '/pay/notify';
                    $result['data'] = self::yxbwechatpay($paras,$payline);
                    break;

                case 'dsh5alipaypay'://鼎盛支付宝h5
                    $paras['notify_url'] = $creUrl . '/pay/notify';
                    $result['data'] = self::dsh5alipaypay($paras,$payline);
                    break;
                case 'dsalipaypay'://鼎盛支付宝
                    $paras['notify_url'] = $creUrl . '/pay/notify';
                    $result['data'] = self::dsalipaypay($paras,$payline);
                    break;
                case 'dsh5wechatpay'://鼎盛宝微信h5
                    $paras['notify_url'] = $creUrl . '/pay/notify';
                    $result['data'] = self::dsh5wechatpay($paras,$payline);
                    break;
                case 'dswechatpay'://鼎盛微信
                    $paras['notify_url'] = $creUrl . '/pay/notify';
                    $result['data'] = self::dswechatpay($paras,$payline);
                    break;
                case 'hmwechatpay'://黑猫微信
                    $paras['notify_url'] = $creUrl . '/pay/hmnotify';
                    $result['data'] = self::hmwechatpay($paras,$payline);
                    break;
                case 'hmalipaypay'://黑猫支付宝
                    $paras['notify_url'] = $creUrl . '/pay/hmnotify';
                    $result['data'] = self::hmalipaypay($paras,$payline);
                    break;
                case 'hmunionpay'://黑猫银联快捷
                    $paras['notify_url'] = $creUrl . '/pay/hmnotify';
                    $result['data'] = self::hmunionpay($paras,$payline);
                    break;
                case 'hmwebpay'://黑猫网银
                    $paras['notify_url'] = $creUrl . '/pay/hmnotify';
                    $result['data'] = self::hmwebpay($paras,$payline);
                    break;
            }
            return $result;
        }
        return $data;
    }
    # endregion

    # region 支付异步通知
    public static function payNotify($paras)
    {
        global $db;
        global $utility;
        //需要处理的页面参数，用来翻页操作及生成缓存键
        $paras['orderid'] = (isset($paras['orderid']) ? $paras['orderid'] : '');

        if(empty($paras['orderid'])){
            $paras['orderid'] = (isset($paras['out_trade_no']) ? $paras['out_trade_no'] : '');
        }
        if( empty($paras['orderid']) ){ //千万家
            $paras['orderid'] = (isset($paras['orderNo']) ? $paras['orderNo'] : '');
        }

        if( empty($paras['orderid']) ){ //密付
            $paras['orderid'] = (isset($paras['billno']) ? $paras['billno'] : '');
        }
        if( empty($paras['orderid']) ){ //三多
            $paras['orderid'] = (isset($paras['out_trade_no']) ? $paras['out_trade_no'] : '');
        }
        if( empty($paras['orderid']) ){ //诚易通
            $paras['orderid'] = (isset($paras['ordernumber']) ? $paras['ordernumber'] : '');
        }
        if( empty($paras['orderid']) ){ //银信宝
            $paras['orderid'] = (isset($paras['outTradeNo']) ? $paras['outTradeNo'] : '');
        }
        if( empty($paras['orderid']) ){ //鼎盛
            $paras['orderid'] = (isset($paras['outTradeNo']) ? $paras['outTradeNo'] : '');
        }
        if( empty($paras['orderid']) ){ //黑猫
            $paras['orderid'] = (isset($paras['order_no']) ? $paras['order_no'] : '');
        }

        if(empty($paras['orderid']))
        {
            return array(
                'state' => 404,
                'msgid' => 404,
                'msg' => 'ORDERID is NULL'
            );
        }
        $db_prefix = \Config\Sys::$dbprefix;

        $sql = "SELECT r.paywayid,w.payclass,r.lineid FROM `{$db_prefix}users_recharge` r,`{$db_prefix}pay_way` w WHERE w.id=r.paywayid AND r.rechargeid='{$paras['orderid']}' LIMIT 1";
        $paywayclass = $db->row($sql);

        $sql = "SELECT * FROM `{$db_prefix}rechargeline` WHERE `id`={$paywayclass['lineid']} LIMIT 1";
        $payline = $db->row($sql);
        $orderQueryFunc = $paywayclass['payclass'].'Notify';

        # 找出对就的充值线路

        return self::$orderQueryFunc($payline,$paras);

    }
    # endregion

    # region 静态二维码支付
    public static function qrcodepay($paras, $payline)
    {
        global $db;
        global $utility;

        $db_prefix = \Config\Sys::$dbprefix;

        # 找出对应银行的图片名称（银行的英文简称）
        $sql = "SELECT `code` FROM `{$db_prefix}bank_list` WHERE `id`={$payline['bankid']} LIMIT 1";
        $bankcode = $db->row($sql);
        $bankcode = $bankcode['code'];
        #组装展示给前台的数据
        $data = array(
            'code' => strtolower($bankcode),
            'qrcodeurl' => str_replace('/upload/','',$payline['posturl']),
            'username' => $payline['username'],
            'memcode' => $payline['memcode'],
            'rechargeid' => $paras['rechargeid'],
            'amount' => number_format($paras['paycoin'], 2, '.', ''),//number_format($paycoin,'',',',2), //折扣后的金额
            'useramount' => number_format($paras['amount'], 2, '.', ''),//number_format($get_args['amount'],'.',',',2),//用户提交的金额
            'times' => date('Y-m-d H:i:s', $paras['nowtime']), //充值时间
        );
        return array(
            'state' => 200,
            'datas' => $data,
            'paytype' => 'qrcodepay',
            'request' => '',
        );
    }

    public static function qrcodepayOrderQuery($orderid, $payline, $paras){
        return array(
            'state' => 404,
            'msgid' => 404, // 支付失败
        );
    }
    # endregion

    # region 银联转帐
    /**
     * 银联转帐
     * @param $paras 参数
     * @param $payline 充值线路
     * @return array 返回数据
     */
    public static function transfer($paras, $payline)
    {
        global $db;
        global $utility;

        $db_prefix = \Config\Sys::$dbprefix;

        # 找出对应银行的图片名称（银行的英文简称）
        $sql = "SELECT `code`,REPLACE(`logo`,'/upload/','') as logo FROM `{$db_prefix}bank_list` WHERE `id`={$payline['bankid']} LIMIT 1";
        $bank = $db->row($sql);
        $bankcode = $bank['code'];
        #组装展示给前台的数据
        $data = array(
            'code' => strtolower($bankcode),
            'name' => $payline['username'],
            'account' => $payline['account'],
            'address' => $payline['openadds'],
            'rechargeid' => $paras['rechargeid'],
            'amount' => number_format($paras['paycoin'], 2, '.', ''),//number_format($paycoin,'',',',2), //折扣后的金额
            'useramount' => number_format($paras['amount'], 2, '.', ''),//number_format($get_args['amount'],'.',',',2),//用户提交的金额
            'times' => date('Y-m-d H:i:s', $paras['nowtime']), //充值时间
            'img'   => $bank['logo']
        );
        return array(
            'state' => 200,
            'datas' => $data,
            'paytype' => 'transfer',
            'request' => '',
        );
    }
    public static function transferOrderName($paras){
        global $db;
        global $utility;
        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'orderid',
            'tname',
        );

        $paras = $utility->get_url_args($paras, $url_args);
        $db_prefix = \Config\Sys::$dbprefix;

        $result =  array(
            'state' => 404,
            'msgid' => 404,
        );

        if(empty($paras['orderid'])){
            return $result;
        }
        if(empty($paras['tname'])){
            return $result;
        }

        $sql = "SELECT `rechargeid` FROM `{$db_prefix}users_recharge` WHERE paywayid=2 AND rechargeid='{$paras['orderid']}' LIMIT 1";
        $rechargelog = $db->row($sql);

        if($rechargelog){
            $sql = "UPDATE `{$db_prefix}users_recharge` SET `transfername`='{$paras['tname']}' WHERE `rechargeid`='{$paras['orderid']}'";
            $updateid = $db->query($sql);
            $result = array(
                'state' => 200,
                'msgid' => 200,
                'update' => $updateid,
            );
        }
        return $result;
    }
    # endregion

    # region 支付宝
    /**
     * 支付宝支付过程
     * @param $paras URL过滤后的参数
     * @param $payline 充值线路
     * @return array 返回数据
     */
    public static function alipay($paras, $payline)
    {
        // 获取支付金额
        $paycoin = floatval($paras['paycoin']);

        $aop = new AopClient;
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = $payline['memcode']; // 支付宝AppID
        $aop->rsaPrivateKey = $payline['rsaprikey'];// 请填写开发者私钥去头去尾去回车，一行字符串
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = $payline['pubkey'];// 请填写支付宝公钥，一行字符串';

        switch ($paras['payfrom']) {
            case 'mobile':
                $request = new AlipayTradeWapPayRequest();
                // 异步通知地址
                $notify_url = urlencode($paras['notify_url']); // 商户外网可以访问的异步地址
                // 订单号，示例代码使用时间值作为唯一的订单ID号
                //$paras['rechargeid'];
                //SDK已经封装掉了公共参数，这里只需要传入业务参数
                $bizcontent = "{\"body\":\"" . $paras['body'] . "\","
                    . "\"subject\": \"" . $paras['subject'] . "\","
                    . "\"out_trade_no\": \"" . $paras['rechargeid'] . "\","
                    . "\"timeout_express\": \"30m\","
                    . "\"total_amount\": \"" . $paycoin . "\","
                    . "\"product_code\":\"QUICK_WAP_WAY\""
                    . "}";
                $request->setNotifyUrl($notify_url);
                $request->setBizContent($bizcontent);
                //这里和普通的接口调用不同，使用的是sdkExecute
                $result = $aop->pageExecute($request);
                break;
            case 'web':
                $request = new AlipayTradePagePayRequest();
                // 异步通知地址
                $notify_url = urlencode($paras['notify_url']); // 商户外网可以访问的异步地址
                // 订单号，示例代码使用时间值作为唯一的订单ID号
                //$paras['rechargeid'];
                //SDK已经封装掉了公共参数，这里只需要传入业务参数
                $bizcontent = "{\"body\":\"" . $paras['body'] . "\","
                    . "\"subject\": \"" . $paras['subject'] . "\","
                    . "\"out_trade_no\": \"" . $paras['rechargeid'] . "\","
                    . "\"timeout_express\": \"30m\","
                    . "\"total_amount\": \"" . $paycoin . "\","
                    . "\"product_code\":\"FAST_INSTANT_TRADE_PAY\""
                    . "}";
                $request->setReturnUrl(urlencode($paras['synchro_url']));
                $request->setNotifyUrl($notify_url);
                $request->setBizContent($bizcontent);
                //这里和普通的接口调用不同，使用的是sdkExecute
                $result = $aop->pageExecute($request);
                break;
            default:
                $request = new AlipayTradeAppPayRequest();
                // 异步通知地址
                $notify_url = urlencode($paras['notify_url']); // 商户外网可以访问的异步地址
                // 订单号，示例代码使用时间值作为唯一的订单ID号
                //$paras['rechargeid'];
                //SDK已经封装掉了公共参数，这里只需要传入业务参数
                $bizcontent = "{\"body\":\"" . $paras['body'] . "\","
                    . "\"subject\": \"" . $paras['subject'] . "\","
                    . "\"out_trade_no\": \"" . $paras['rechargeid'] . "\","
                    . "\"timeout_express\": \"30m\","
                    . "\"total_amount\": \"" . $paycoin . "\","
                    . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                    . "}";
                $request->setNotifyUrl($notify_url);
                $request->setBizContent($bizcontent);
                //这里和普通的接口调用不同，使用的是sdkExecute
                $result = $aop->sdkExecute($request);
            //print_r($response);
            // 注意：这里不需要使用htmlspecialchars进行转义，直接返回即可
        }
        return array(
            'state' => 200,
            'datas' => $result,
            'orderid' => $paras['rechargeid'],
            'paytype' => 'alipay',
        );
    }

    # region 支付宝订单查询
    private static function alipayOrderQuery($orderid, $payline, $paras){
        $aop = new AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $payline['memcode'];
        $aop->rsaPrivateKey = $payline['rsaprikey']; // 请填写开发者私钥去头去尾去回车，一行字符串;
        $aop->alipayrsaPublicKey= $payline['pubkey'] ;//请填写支付宝公钥，一行字符串';
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new AlipayTradeQueryRequest();

        $request->setBizContent("{" .
            "\"out_trade_no\":\"".$orderid."\"," .
            "\"trade_no\":\"\"" .
            "}");
        $result = $aop->execute($request);
        if(empty($result)){
            return array(
                'state' => 404,
                'msgid' => 10078, // 支付失败
                'msg' => ''
            );
        }

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode) && intval($resultCode) == 10000){
            // print_r($result->$responseNode);
            if($result->$responseNode->trade_status == 'TRADE_SUCCESS') {
                # 成功 - 开始确认动作;
                return self::ConfirmUserRecharge($orderid, $result->$responseNode->total_amount);
            }else{
                # 调用成功，但没有支付成功
                return array(
                    'state' => 404,
                    'msgid' => 10078, // 支付失败
                    'msg' => $result->$responseNode->trade_status,// 失败信息
                );
            }
        } else {
            # 失败
            return array(
                'state' => 404,
                'msgid' => 10078, // 支付失败
                'msg' => $result->$responseNode->msg,// 失败信息
            );
        }
    }
    # endregion

    # 支付宝异步通知
    private static function alipayNotify($payline, $paras)
    {

    }
    # endregion

    # region PaysApi
    public static function paysapialipay($paras, $payline)
    {
        return self::paysApiGetCodeToUrl($paras, $payline, 1); // 支付渠道：1-支付宝；2-微信支付
    }
    public static function paysapiwxpay($paras, $payline)
    {
        return self::paysApiGetCodeToUrl($paras, $payline, 2); // 支付渠道：1-支付宝；2-微信支付
    }
    public static function paysApiGetCodeToUrl($paras, $payline, $istype)
    {
        //从网页传入price:支付价格， istype:支付渠道：1-支付宝；2-微信支付
        $price = $paras['paycoin'];

        $orderuid = $paras['uno'];       //此处传入您网站用户的用户名，方便在paysapi后台查看是谁付的款，强烈建议加上。可忽略。

        //校验传入的表单，确保价格为正常价格（整数，1位小数，2位小数都可以），支付渠道只能是1或者2，orderuid长度不要超过33个中英文字。

        //此处就在您服务器生成新订单，并把创建的订单号传入到下面的orderid中。
        $goodsname = $paras['subject']; //"请叫我商品名称，不要超过33个中英文字";
        $orderid = $paras['rechargeid'];    //每次有任何参数变化，订单号就变一个吧。
        $uid = $payline['memcode'];//"此处填写PaysApi的uid";
        $token = $payline['md5key'];//"此处填写PaysApi的Token";
        $return_url = $paras['synchro_url']; // 'http://www.demo.com/payreturn.php';
        $notify_url = $paras['notify_url']; // 'http://www.demo.com/paynotify.php';

        $key = md5($goodsname. $istype . $notify_url . $orderid . $orderuid . $price . $return_url . $token . $uid);
        //经常遇到有研发问为啥key值返回错误，大多数原因：1.参数的排列顺序不对；2.上面的参数少传了，但是这里的key值又带进去计算了，导致服务端key算出来和你的不一样。

        $returndata['goodsname'] = $goodsname;
        $returndata['istype'] = $istype;
        $returndata['key'] = $key;
        $returndata['notify_url'] = $notify_url;
        $returndata['orderid'] = $orderid;
        $returndata['orderuid'] =$orderuid;
        $returndata['price'] = $price;
        $returndata['return_url'] = $return_url;
        $returndata['uid'] = $uid;
        return self::PaysApiJsonSuccess("OK",$returndata,"");
    }
    private static function paysapialipayOrderQuery($orderid, $payline, $paras)
    {
        return self::paysapiOrderQuery($orderid, $payline, $paras);
    }
    private static function paysapiwxpayOrderQuery($orderid, $payline, $paras)
    {
        return self::paysapiOrderQuery($orderid, $payline, $paras);
    }
    private static function paysapialipayNotify($payline, $paras)
    {
        return self::paysapiNotify($payline, $paras);
    }
    private static function paysapiwxpayNotify($payline, $paras)
    {
        return self::paysapiNotify($payline, $paras);
    }
    private static function paysapiNotify($payline, $paras)
    {
        $paysapi_id = $paras["paysapi_id"];
        $orderid = $paras["orderid"];
        $price = $paras["price"];
        $realprice = $paras["realprice"];
        $orderuid = $paras["orderuid"];
        $key = $paras["key"];

        //校验传入的参数是否格式正确，略

        $token = $payline['md5key'];

        $temps = md5($orderid . $orderuid . $paysapi_id . $price . $realprice . $token);

        $result = array();

        if ($temps != $key){
            $result['data'] = self::PaysApiJsonError("key值不匹配");
        }else{
            //校验key成功，是自己人。执行自己的业务逻辑：加余额，订单付款成功，装备购买成功等等。
            $result['data'] = self::ConfirmUserRecharge($orderid, $realprice);
        }
        return $result;
    }
    private static function paysapiOrderQuery($orderid, $payline, $paras){

        global $utility;

        // uid + orderid + r + token

        $arr = array(
            'uid' => $payline['memcode'],
            'orderid' => $paras['orderid'],
            'r' => time(),
            'key' => $payline['md5key'],
        );

        $sign = md5($arr['uid'] . $arr['orderid'] . $arr['r'] . $payline['md5key']);

        $arr['key'] = strtolower($sign);

        $url = 'https://api.paysapi.com/get_order_staus_by_id?uid='.$arr['uid'].'&orderid='.$arr['orderid'].'&r='.$arr['r'].'&key='.$arr['key'];

        $curl = $utility->curl_get_https($url);

        $request = json_decode($curl, true);

        //print_r($request);
        //print_r($paras);


        if ($request['code'] == '1'){
            if($request['data']['status']==1) {
                //校验key成功，是自己人。执行自己的业务逻辑：加余额，订单付款成功，装备购买成功等等。
                return self::ConfirmUserRecharge($orderid, $payline['amount']);
            }else{
                return array(
                    'state' => 404,
                    'msgid' => 10078, // 支付失败
                    'msg' => $request['msg'],// 失败信息
                );
            }

        }else{
            return array(
                'state' => 404,
                'msgid' => 10078, // 支付失败
                'msg' => $request['msg'],// 失败信息
            );
            //return self::PaysApiJsonError($request['msg']);
        }
    }
    //返回错误
    public static function PaysApiJsonError($message = '',$url=null)
    {
        return array(
            'state' => 200,
            'datas' => array(
                'msg' => $message,
                'data' => '',
                'code' => -1,
                'url' => $url,
            ),
            'paytype' => 'paysapialipay',
        );
    }

    //返回正确
    public static function PaysApiJsonSuccess($message = '',$data = '',$url=null)
    {
        return array(
            'state' => 200,
            'datas' => array(
                'msg' => $message,
                'data' => $data,
                'code' => 1,
                'url' => $url,
            ),
            'paytype' => ($data['istype']==1 ? 'paysapialipay' : 'paysapiwxpay'),
        );
    }
    # endregion

    # region 微信APP支付
    public static function wxpayapp($paras, $payline)
    {
        // 获取支付金额
        $paycoin = floatval($paras['paycoin']);

        $paycoin = round($paycoin*100); // 将元转成分

        $payline['notify_url'] = $paras['notify_url'];
        $payline['REMOTE_ADDR'] = '112.97.60.81';//long2ip($paras['remoteip']);

        $unifiedOrder = new WxPayUnifiedOrder();
        $unifiedOrder->SetBody($paras['subject']);//商品或支付单简要描述
        $unifiedOrder->SetOut_trade_no($paras['rechargeid']);
        $unifiedOrder->SetTotal_fee($paycoin);
        $unifiedOrder->SetTrade_type("APP");
        //var_dump($unifiedOrder);
        $result = WxPayApi::unifiedOrder($unifiedOrder, $payline, 30);

        if($result['return_code']!='FAIL') {
            $parmpts = array(
                'appid' => $result['appid'],
                'noncestr' => $result['nonce_str'],
                'package' => 'Sign=WXPay',
                'partnerid' => $result['mch_id'],
                'prepayid' => $result['prepay_id'],
                'timestamp' => intval(time()),
            );

            $string = 'appid=' . $parmpts['appid'] . '&noncestr=' . $parmpts['noncestr'];
            $string .= '&package=Sign=WXPay&partnerid=' . $parmpts['partnerid'];
            $string .= '&prepayid=' . $parmpts['prepayid'] . '&timestamp=' . $parmpts['timestamp'] . '&key=' . $payline['md5key'];


            $sign = md5($string);
            $parmpts['sign'] = strtoupper($sign);

            return array(
                'state' => 200,
                'datas' => $parmpts,
                'request' => $result,
                'orderid' => $paras['rechargeid'],
                'paytype' => 'wxpayapp',
            );
        }else{
            return array(
                'state' => 404,
                'msgid' => 10077,
                'msg' => $result['return_msg'],
                'orderid' => $paras['rechargeid'],
                'paytype' => 'wxpayapp',
            );
        }
    }
    # endregion

    # region 微信H5订单查询
    private static function wxpayappOrderQuery($orderid, $payline, $paras){
        $unifiedOrder = new WxPayUnifiedOrder();
        $unifiedOrder->SetOut_trade_no($orderid);
        $result = WxPayApi::orderQuery($unifiedOrder, $payline, 30);

        if($result['result_code']!='SUCCESS' && $result['return_code']!='SUCCESS'){
            return array(
                'state' => 404,
                'msgid' => 10078, // 支付失败
                'msg' => ''
            );
        }
        $resultCode = (isset($result['trade_state']) ? $result['trade_state'] : '');
        if(!empty($resultCode) && $resultCode == 'SUCCESS'){
            $total_fee = $result['total_fee'] / 100;
            # 成功 - 开始确认动作;
            return self::ConfirmUserRecharge($orderid, $total_fee);
        } else {
            # 失败
            return array(
                'state' => 404,
                'msgid' => 10078, // 支付失败
                'msg' => '',// 失败信息
            );
        }
    }
    # endregion

    # region微信异步通知
    private static function wxpayappNotify($payline, $paras)
    {
        return 'SUCCESS';
        /*
        if(isset($paras['trade_status']) && $paras['trade_status'] == 'TRADE_SUCCESS'){
            # 成功 - 开始确认动作;
            return self::ConfirmUserRecharge($paras['orderid'], $paras['buyer_pay_amount']);
        } else {
            # 失败
            return array(
                'state' => 404,
                'msgid' => 10078, // 支付失败
                'msg' => '',// 失败信息
            );
        }
        */
    }
    # endregion

    # region 支付宝H5支付
    public static function alipayh5($paras, $payline){

    }
    # endregion

    # region 微信H5支付
    public static function weixinh5($paras, $payline)
    {
        // 获取支付金额
        $paycoin = floatval($paras['paycoin']);

        $paycoin = round($paycoin*100); // 将元转成分

        $payline['notify_url'] = $paras['notify_url'];
        $payline['REMOTE_ADDR'] = long2ip($paras['remoteip']);

        $result['return_code'] = 'FAIL';
        $result['return_msg'] = '连接微信服务器超时';

        // print_r('开始组装支付订单....');
        // print_r($payline);
        try {
            $unifiedOrder = new WxPayUnifiedOrder();
            $unifiedOrder->SetBody($paras['subject']);//商品或支付单简要描述
            $unifiedOrder->SetOut_trade_no($paras['rechargeid']);
            $unifiedOrder->SetTotal_fee($paycoin);
            $unifiedOrder->SetTrade_type("MWEB");
            $result = WxPayApi::unifiedOrder($unifiedOrder, $payline, 6);
        }catch (Exception $e){
            var_dump($e->getMessage());
        }
        // print_r('组装完成....');
        //print_r($result);

        if($result['return_code']!='FAIL') {
            $parmpts = array(
                'appid' => $result['appid'],
                'noncestr' => $result['nonce_str'],
                'package' => 'Sign=WXPay',
                'partnerid' => $result['mch_id'],
                'prepayid' => $result['prepay_id'],
                'timestamp' => intval(time()),
            );
            // 'scene_info' => '{"h5_info":{"type": "wap","wap_url": "http://pay.baozhuodipu.com","wap_name": "宝卓迪普"}}',
            $string = 'appid=' . $parmpts['appid'] . '&noncestr=' . $parmpts['noncestr'];
            $string .= '&package=Sign=WXPay&partnerid=' . $parmpts['partnerid'];
            $string .= '&prepayid=' . $parmpts['prepayid'] . '&timestamp=' . $parmpts['timestamp'] . '&key=' . $payline['md5key'];


            $sign = md5($string);
            $parmpts['sign'] = strtoupper($sign);

            return array(
                'state' => 200,
                //'datas' => $parmpts,
                //'request' => $result,
                'orderid' => $paras['rechargeid'],
                'creurl' => $payline['creurl'],
                'mweburl' => $result['mweb_url'],
                'paytype' => 'weixinh5',
            );
        }else{
            return array(
                'state' => 404,
                'msgid' => 10077,
                'msg' => $result['return_msg'],
                'paytype' => 'weixinh5',
            );
        }
    }
    # endregion

    # region 微信H5订单查询
    private static function weixinh5OrderQuery($orderid, $payline, $paras){
        return self::wxpayappOrderQuery($orderid, $payline, $paras);
    }
    # endregion

    # region 多得宝 - 在线支付
    public static function ddbpay($paras, $payline)
    {
        $postUrl = $payline['posturl']; //'https://pay.ztbaopay.com/gateway?input_charset=UTF-8';
        $priKey= openssl_pkey_get_private($payline['rsaprikey']);
        $merchant_code = $payline['memcode'];
        $service_type ="direct_pay";
        $interface_version ="V3.0";
        $pay_type = "";
        $sign_type ="RSA-S";
        $input_charset = "UTF-8";
        $notify_url = $paras['notify_url'];
        $order_no = $paras['rechargeid'];
        $order_time = date("Y-m-d H:i:s",time());//"2015-07-27 14:30:25";
        $order_amount = $paras['paycoin'];
        $product_name ="订单充值";
        $product_code = "";
        $product_desc = "";
        $product_num = "";
        $show_url = "";
        $client_ip ="" ;
        $bank_code = "";
        $redo_flag = "";
        $extend_param = "";
        $extra_return_param = "";
        $return_url = $paras['synchro_url'];

        $signStr= "";
        if($bank_code != ""){
            $signStr = $signStr."bank_code=".$bank_code."&";
        }
        if($client_ip != ""){
            $signStr = $signStr."client_ip=".$client_ip."&";
        }
        if($extend_param != ""){
            $signStr = $signStr."extend_param=".$extend_param."&";
        }
        if($extra_return_param != ""){
            $signStr = $signStr."extra_return_param=".$extra_return_param."&";
        }

        $signStr = $signStr."input_charset=".$input_charset."&";
        $signStr = $signStr."interface_version=".$interface_version."&";
        $signStr = $signStr."merchant_code=".$merchant_code."&";
        $signStr = $signStr."notify_url=".$notify_url."&";
        $signStr = $signStr."order_amount=".$order_amount."&";
        $signStr = $signStr."order_no=".$order_no."&";
        $signStr = $signStr."order_time=".$order_time."&";

        if($pay_type != ""){
            $signStr = $signStr."pay_type=".$pay_type."&";
        }

        if($product_code != ""){
            $signStr = $signStr."product_code=".$product_code."&";
        }
        if($product_desc != ""){
            $signStr = $signStr."product_desc=".$product_desc."&";
        }

        $signStr = $signStr."product_name=".$product_name."&";

        if($product_num != ""){
            $signStr = $signStr."product_num=".$product_num."&";
        }
        if($redo_flag != ""){
            $signStr = $signStr."redo_flag=".$redo_flag."&";
        }
        if($return_url != ""){
            $signStr = $signStr."return_url=".$return_url."&";
        }

        if($show_url != ""){

            $signStr = $signStr."service_type=".$service_type."&";
            $signStr = $signStr."show_url=".$show_url;
        }else{

            $signStr = $signStr."service_type=".$service_type;
        }
        $sign_info = "";

        openssl_sign($signStr,$sign_info,$priKey,OPENSSL_ALGO_MD5);
        $sign = base64_encode($sign_info);

        return array(
            'state' => 200,
            'paytype' => 'ddbpay',
            'data' => array(
                'posturl' => $postUrl,
                'sign' => $sign,
                'merchant_code' => $merchant_code,
                'bank_code' => $bank_code,
                'order_no' => $order_no,
                'order_amount' => $order_amount,
                'service_type' => $service_type,
                'input_charset' => $input_charset,
                'notify_url' => $notify_url,
                'interface_version' => $interface_version,
                'sign_type' => $sign_type,
                'order_time' => $order_time,
                'product_name' => $product_name,
                'client_ip' => $client_ip,
                'extend_param' => $extend_param,
                'extra_return_param' => $extra_return_param,
                'pay_type' => $pay_type,
                'product_code' => $product_code,
                'product_desc' => $product_desc,
                'product_num' => $product_num,
                'return_url' => $return_url,
                'show_url' => $show_url,
                'redo_flag' => $redo_flag,
            ),
        );

    }
    # endregion

    # region 千万家 - 在线支付
    public static function qwjwxcodepay($paras, $payline)//微信扫码支付
    {
        return self::qwjGetParamsToUrl($paras, $payline, '01');
    }
    public static function qwjwxh5pay($paras, $payline)//微信h5
    {
        return self::qwjGetParamsToUrl($paras, $payline, '02');
    }
    public static function qwjalipaycodepay($paras, $payline)//支付宝扫码
    {
        return self::qwjGetParamsToUrl($paras, $payline, '11');
    }
    public static function qwjalipaywappay($paras, $payline)//支付宝wap
    {
        return self::qwjGetParamsToUrl($paras, $payline, '12');
    }
    public static function qwjtransfercodepay($paras,$payline)//银联扫码
    {
        return self::qwjGetParamsToUrl($paras, $payline, '71');
    }
    public static function qwjGetParamsToUrl($paras,$payline,$istype)
    {
        switch ( $istype ){
            case '01':
                $paytype = 'qwjwxcodepay';
                break;
            case '02':
                $paytype = 'qwjwxh5pay';
                break;
            case '11':
                $paytype = 'qwjalipaycodepay';
                break;
            case '12':
                $paytype = 'qwjalipaywappay';
                break;
            case '71':
                $paytype = 'qwjtransfercodepay';
                break;
            default :
                $paytype = '';
                break;
        }
        $returnUrl = $paras['synchro_url']; // 'http://www.demo.com/payreturn.php';
        $notifyUrl = $paras['notify_url'];

        $userId = $payline['memcode'];//"平台提供给商户的ID";
        $orderNo = $paras['rechargeid'];//商户交易号
        $tradeType = $istype;//交易类型
        $payAmt = $paras['paycoin'];//支付金额单位：元
        $bankId = isset($paras['bankid']) ? $paras['bankid'] : '';
        $goodsName = $paras['subject'];//商品名称
        $goodsDesc = '';

        $price = $paras['paycoin'];

        $key = $payline['md5key'];//"此处填写PaysApi的Token";
        $sign_str = '';
        $sign_str = $sign_str . 'notifyUrl=' . $notifyUrl;
        $sign_str = $sign_str . '&orderNo=' . $orderNo;
        $sign_str = $sign_str . '&payAmt=' . $payAmt;
        $sign_str = $sign_str . '&returnUrl=' . $returnUrl;
        $sign_str = $sign_str . '&tradeType=' . $tradeType;
        $sign_str = $sign_str . '&userId=' . $userId;
        $sign_str = $sign_str . '&key=' . $key;
        $sign = md5($sign_str);
        //经常遇到有研发问为啥key值返回错误，大多数原因：1.参数的排列顺序不对；2.上面的参数少传了，但是这里的key值又带进去计算了，导致服务端key算出来和你的不一样。
        $postData = [
            'userId'    => $userId,
            'orderNo'   => $orderNo,
            'tradeType' => $tradeType,
            'payAmt'    => $price,
            'goodsName' => $goodsName,
            'returnUrl' => $returnUrl,
            'notifyUrl' => $notifyUrl,
            'sign'      => $sign
        ];
        $res = self::post('http://pay.qwj8686.com/orderpay.do',$postData);
        $arr = json_decode($res,true);
        if( $arr['retCode'] == 0 ){
            return [
                'state'     => 200,
                'orderid'   => $arr['orderNo'],
                'payurl'    => $arr['payUrl'],
                'paytype'   => $paytype,
            ];
        }else{
            self::userRechargeError($orderNo);
            return [
                'state' => 404,
                'msgid' => 10078,
                'msg'   => $arr['retMsg'],
                'paytype' => $paytype,
            ];
        }

    }
    private static function qwjwxcodepayNotify($payline, $paras)
    {
        return self::qwjpayNotify($payline, $paras);
    }
    private static function qwjwxh5paypayNotify($payline, $paras)
    {
        return self::qwjpayNotify($payline, $paras);
    }
    private static function qwjalipaycodepayNotify($payline, $paras)
    {
        return self::qwjpayNotify($payline, $paras);
    }
    private static function qwjalipaywappayNotify($payline, $paras)
    {
        return self::qwjpayNotify($payline, $paras);
    }
    private static function qwjtransfercodepayNotify($payline, $paras)
    {
        return self::qwjpayNotify($payline, $paras);
    }
    private static function qwjpayNotify($payline, $paras)
    {
        if( $paras['retCode'] == 0 ){
            self::ConfirmUserRecharge($paras['orderNo'],$paras['payAmt']);
            return ['state' => 200,'msg'=>'success'];
        }elseif ($paras['retCode'] == 1){
            self::userRechargeError($paras['orderNo']);
        }
        return ['state' => 404,'msg'=>'error'];
    }
    private static function qwjwxcodepayOrderQuery($orderid, $payline, $paras)
    {
        self::qwjpayOrderQuery($orderid, $payline, $paras);
    }
    private static function qwjwxh5payOrderQuery($orderid, $payline, $paras)
    {
        self::qwjpayOrderQuery($orderid, $payline, $paras);
    }
    private static function qwjalipaycodepayOrderQuery($orderid, $payline, $paras)
    {
        self::qwjpayOrderQuery($orderid, $payline, $paras);
    }
    private static function qwjtransfercodepayOrderQuery($orderid, $payline, $paras)
    {
        self::qwjpayOrderQuery($orderid, $payline, $paras);
    }
    private static function qwjpayOrderQuery($orderid, $payline, $paras)
    {
        global $db;
        $userId = $payline['memcode'];
        $orderNo = $orderid;
        $key = $payline['md5key'];
        $sign_str = '';
        $sign_str = $sign_str . 'orderNo=' . $orderNo;
        $sign_str = $sign_str . '&userId=' . $userId;
        $sign_str = $sign_str . '&key=' . $key;
        $sign = md5($sign_str);
        $params = [
            'userId' => $userId,
            'orderNo'=> $orderNo,
            'sign'   => $sign
        ];
        $url = 'http://pay.qwj8686.com/orderquery.do';
        $curl = self::post($url,$params);
        $request = json_decode($curl, true);
        if( $request['status'] == 1 ){
            return self::ConfirmUserRecharge($orderid, $payline['amount']);
        }elseif($request['status'] == 0){
            return [
                'state' => 200,
                'msgid' => 10115, // 支付失败
                'msg' => '等待支付',// 失败信息
            ];
        }elseif( $request['status'] == 7 ){
            return [
                'state' => 200,
                'msg' => '用户支付中',// 失败信息
            ];
        }else{
            self::userRechargeError($orderNo);
            return [
                'state' => 404,
                'msgid' => 10115, // 支付失败
                'msg' => '支付失败',// 失败信息
            ];
        }
    }
    # endregion

    # region 密付支付
    public static function mfunionpay($paras,$payline) //银联扫码
    {
        return self::mfGetParamsToUrl($paras,$payline,'UNION');
    }
    public static function mfh5unionpay($paras,$payline) //银联h5
    {
        return self::mfGetParamsToUrl($paras,$payline,'H5_UNION');
    }
    public static function mfkuaijiepay($paras,$payline) //快捷支付
    {
        return self::mfGetParamsToUrl($paras,$payline,'KUAIJIE');
    }
    public static function mfalipaypay($paras,$payline) // 支付宝扫码
    {
        return self::mfGetParamsToUrl($paras,$payline,'ALIPAY');
    }
    public static function mfwechatpay($paras,$payline) //微信扫码
    {
        return self::mfGetParamsToUrl($paras,$payline,'WECHAT');
    }
    public static function mfqqpay($paras,$payline) //qq
    {
        return self::mfGetParamsToUrl($paras,$payline,'QQ');
    }
    public static function mfh5wechatpay($paras,$payline) //微信h5
    {
        return self::mfGetParamsToUrl($paras,$payline,'H5_WECHAT');
    }
    public static function mfh5alipaypay($paras,$payline) //支付宝h5
    {
        return self::mfGetParamsToUrl($paras,$payline,'H5_ALIPAY');
    }
    public static function mfh5qqpay($paras,$payline) //qqh5
    {
        return self::mfGetParamsToUrl($paras,$payline,'H5_QQ');
    }
    public static function mfunionqrpay($paras,$payline) //云闪付扫码
    {
        return self::mfGetParamsToUrl($paras,$payline,'UNION_QR');
    }
    public static function mfGetParamsToUrl($paras,$payline,$istype)
    {
        switch ( $istype ){
            case 'UNION':
                $paytype = 'mfunionpay';
                break;
            case 'H5_UNION':
                $paytype = 'mfh5unionpay';
                break;
            case 'KUAIJIE':
                $paytype = 'mfkuaijiepay';
                break;
            case 'ALIPAY':
                $paytype = 'mfalipaypay';
                break;
            case 'WECHAT':
                $paytype = 'mfwechatpay';
                break;
            case 'QQ':
                $paytype = 'mfqqpay';
                break;
            case 'H5_WECHAT':
                $paytype = 'mfh5wechatpay';
                break;
            case 'H5_QQ':
                $paytype = 'mfh5qqpay';
                break;
            case 'UNION_QR':
                $paytype = 'mfunionqrpay';
                break;
            case 'H5_ALIPAY':
                $paytype = 'mfh5alipaypay';
                break;
            default :
                $paytype = '';
                break;
        }
        $merchant = $payline['memcode'];//"平台提供给商户的ID";
        $billno = $paras['rechargeid'];//商户交易号
        $amount = $paras['paycoin'];//支付金额单位：元
        $return_url = $paras['synchro_url']; // 'http://www.demo.com/payreturn.php';
        $notify_url = $paras['notify_url'];
        $device = 2;//默认pc
        $sign_type = 'MD5'; //加密方式
        $bank = $istype;//交易类型
        $pay_time = date('YmdHis',time());
        $key = $payline['md5key'];
        $sign_str = '';
        $sign_str = $sign_str . 'amount=' . $amount;
        $sign_str = $sign_str . '&bank=' . $bank;
        $sign_str = $sign_str . '&billno=' . $billno;
        $sign_str = $sign_str . '&merchant=' . $merchant;
        $sign_str = $sign_str . '&pay_time=' . $pay_time;
        $sign_str = $sign_str . '&sign_type=' . $sign_type;
        $sign_str = $sign_str . '&key=' . $key;
        $sign = md5($sign_str);
        $data = [
            'merchant'  => $merchant,
            'billno'    => $billno,
            'pay_time'  => $pay_time,
            'amount'    => $amount,
            'sign_type' => $sign_type,
            'bank'      => $bank,
            'notify_url'=> $notify_url,
            'return_url'=> $return_url,
            'sign'      => $sign,
            'device'    => $device
        ];
        if( $istype == 'H5_ALIPAY' || $istype == 'H5_QQ' || $istype == 'H5_UNION' || $istype == 'H5_WECHAT' ){
            $res = self::post('https://api.mpaymart.com/pay',$data);
            $arr = json_decode($res,true);
            if( $arr['code'] === '1000' ){
                return [
                    'state' => 200,
                    'datas' => $arr,
                    'paytype' => $paytype,
                ];
            }else{
                self::userRechargeError($billno);
                return [
                    'state' => 404,
                    'msgid' => 10078,
                    'msg'   => '支付失败',
                ];
            }
        }
        return [
            'state' => 200,
            'datas' => $data,
            'paytype' => $paytype,
        ];
    }
    public static function mfunionpayOrderQuery($orderid, $payline, $paras)
    {
        self::mfpayOrderQuery($orderid, $payline, $paras);
    }
    public static function mfh5unionpayOrderQuery($orderid, $payline, $paras)
    {
        self::mfpayOrderQuery($orderid, $payline, $paras);
    }
    public static function mfkuaijiepayOrderQuery($orderid, $payline, $paras)
    {
        self::mfpayOrderQuery($orderid, $payline, $paras);
    }
    public static function mfalipaypayOrderQuery($orderid, $payline, $paras)
    {
        self::mfpayOrderQuery($orderid, $payline, $paras);
    }
    public static function mfwechatpayOrderQuery($orderid, $payline, $paras)
    {
        self::mfpayOrderQuery($orderid, $payline, $paras);
    }
    public static function mfqqpayOrderQuery($orderid, $payline, $paras)
    {
        self::mfpayOrderQuery($orderid, $payline, $paras);
    }
    public static function mfh5wechatpayOrderQuery($orderid, $payline, $paras)
    {
        self::mfpayOrderQuery($orderid, $payline, $paras);
    }
    public static function mfh5alipaypayOrderQuery($orderid, $payline, $paras)
    {
        self::mfpayOrderQuery($orderid, $payline, $paras);
    }
    public static function mfh5qqpayOrderQuery($orderid, $payline, $paras)
    {
        self::mfpayOrderQuery($orderid, $payline, $paras);
    }
    public static function mfunionqrpayOrderQuery($orderid, $payline, $paras)
    {
        self::mfpayOrderQuery($orderid, $payline, $paras);
    }
    private static function mfpayOrderQuery($orderid, $payline, $paras)
    {
        global $db;
        $merchant = $payline['memcode']; //商户号
        $billno = $orderid;
        $amount = (int)$payline['amount'];
        $sign_type = 'MD5';
        $pay_time = date('Ymd');
        $key = $payline['md5key'];

        $sign_str = '';
        $sign_str = $sign_str . 'amount=' . $amount;
        $sign_str = $sign_str . '&billno=' . $billno;
        $sign_str = $sign_str . '&merchant=' . $merchant;
        $sign_str = $sign_str . '&pay_time=' . $pay_time;
        $sign_str = $sign_str . '&sign_type=' . $sign_type;
        $sign_str = $sign_str . '&key=' . $key;
        $sign = md5($sign_str);

        $params = [
            'billno'    => $billno,
            'amount'    => (int)$amount,
            'merchant'  => $merchant,
            'sign_type' => $sign_type,
            'pay_time'  => $pay_time,
            'sign'      => $sign
        ];
        $url = 'https://api.mpaymart.com/pay/query';
        $curl = self::post($url,$params);
        $request = json_decode($curl, true);
        if( $request['code'] === '1000' ){
            if( $request['status'] === 100 ){
                return [
                    'state' => 404,
                    'msg' => '支付中',// 失败信息
                ];
            }elseif( $request['status'] === 110 ){
                return self::ConfirmUserRecharge($orderid, $payline['paid_amount']);
            }else{
                self::userRechargeError($billno);
                return [
                    'state' => 404,
                    'msgid' => 10115, // 支付失败
                    'msg' => '支付失败',// 失败信息
                ];
            }
        }else{
            self::userRechargeError($billno);
            return [
                'state' => 404,
                'msgid' => 10115, // 支付失败
                'msg' => '支付失败',// 失败信息
            ];
        }
    }
    private static function mfunionpayNotify($payline, $paras)
    {
        return self::mfpayNotify($payline, $paras);
    }
    private static function mfh5unionpayNotify($payline, $paras)
    {
        return self::mfpayNotify($payline, $paras);
    }
    private static function mfkuaijiepayNotify($payline, $paras)
    {
        return self::mfpayNotify($payline, $paras);
    }
    private static function mfalipaypayNotify($payline, $paras)
    {
        return self::mfpayNotify($payline, $paras);
    }
    private static function mfwechatpayNotify($payline, $paras)
    {
        return self::mfpayNotify($payline, $paras);
    }
    private static function mfqqpayNotify($payline, $paras)
    {
        return self::mfpayNotify($payline, $paras);
    }
    private static function mfh5wechatpayNotify($payline, $paras)
    {
        return self::mfpayNotify($payline, $paras);
    }
    private static function mfh5alipaypayNotify($payline, $paras)
    {
        return self::mfpayNotify($payline, $paras);
    }
    private static function mfh5qqpayNotify($payline, $paras)
    {
        return self::mfpayNotify($payline, $paras);
    }
    private static function mfunionqrpayNotify($payline, $paras)
    {
        return self::mfpayNotify($payline, $paras);
    }
    private static function mfpayNotify($payline, $paras)
    {
        if( $paras['code'] === '1000' ){
            self::ConfirmUserRecharge($paras['billno'],$paras['paid_amount']);
            return ['state'=>200,'msg'=>'SUCCESS'];
        }else{
            self::userRechargeError($paras['billno']);
            return ['state'=>404,'msg'=>'error'];
        }

    }
    # endregion

    #region 三多支付
    public static function sdh5alipaypay($paras,$payline) //支付宝h5
    {
        return self::sdGetParamsToUrl($paras,$payline,'ali_h5');
    }
    public static function sdalipaypay($paras,$payline) //支付宝扫码
    {
        return self::sdGetParamsToUrl($paras,$payline,'ali_qr');
    }
    public static function sdh5wechatpay($paras,$payline) //微信h5
    {
        return self::sdGetParamsToUrl($paras,$payline,'wx_h5');
    }
    public static function sdwechatpay($paras,$payline) //微信扫码
    {
        return self::sdGetParamsToUrl($paras,$payline,'wx_qr');
    }
    public static function sdGetParamsToUrl($paras,$payline,$istype)
    {
        switch ( $istype ){
            case 'ali_h5':
                $paytype = 'sdh5alipaypay';
                break;
            case 'ali_qr':
                $paytype = 'sdalipaypay';
                break;
            case 'wx_h5':
                $paytype = 'sdh5wechatpay';
                break;
            case 'wx_qr':
                $paytype = 'sdwechatpay';
                break;
            default:
                $paytype = '';
                break;
        }

        $Trade_No = $paras['rechargeid']; //订单号
        $Price = intval($paras['paycoin'] * 100); //以分为单位
        $ChannelType = $istype; //通道类型
        $NotifyUrl = $paras['notify_url'];
        $LoginName = $payline['memcode'];

        $sign_str = $LoginName.$payline['md5key'].$Trade_No.$Price;
        $sign = strtoupper(MD5($sign_str));
        $data = [
            'Trade_No'  => $Trade_No,
            'Price'     => $Price,
            'ChannelType' => $ChannelType,
            'NotifyUrl' => $NotifyUrl,
            'LoginName' => $LoginName,
            'Sign'      => $sign
        ];
        $arr = self::http('http://1.yesmaile.com/admin/httphand/CreateOrder.ashx',$data,true);

        if( $arr['Status'] == 1 ){
            return [
                'state' => 200,
                'datas' => $arr,
                'paytype' => $paytype,
            ];
        }else{
            self::userRechargeError($Trade_No);
            return [
                'state' => 404,
                'msgid' => 10078,
                'msg'   => '支付失败',
            ];
        }
    }
    public static function sdh5alipaypayOrderQuery($orderid, $payline, $paras) //支付宝h5订单查询
    {
        self::sdpayOrderQuery($orderid, $payline, $paras);
    }
    public static function sdalipaypayOrderQuery($orderid, $payline, $paras) //支付宝扫码查询
    {
        self::sdpayOrderQuery($orderid, $payline, $paras);
    }
    public static function sdh5wechatpayOrderQuery($orderid, $payline, $paras) //微信h5查询
    {
        self::sdpayOrderQuery($orderid, $payline, $paras);
    }
    public static function sdwechatpayOrderQuery($orderid, $payline, $paras) //微信扫码查询
    {
        self::sdpayOrderQuery($orderid, $payline, $paras);
    }
    private static function sdh5alipaypayNotify($payline, $paras) //支付宝h5回调
    {
        $res = self::ConfirmUserRecharge($paras['out_trade_no'],$paras['price']);
        if( $res['state'] == 200 ){
            return ['state' => 200,'msg' => true];
        }else{
            self::userRechargeError($paras['out_trade_no']);
            return ['state'=>404,'msg'=>false];
        }
    }
    private static function sdalipaypayNotify($payline, $paras) //支付宝扫码回调
    {
        $res = self::ConfirmUserRecharge($paras['out_trade_no'],$paras['price']);
        if( $res['state'] == 200 ){
            return ['state' => 200,'msg' => true];
        }else{
            self::userRechargeError($paras['out_trade_no']);
            return ['state'=>404,'msg'=>false];
        }
    }
    private static function sdh5wechatpayNotify($payline, $paras) //微信h5回调
    {
        $res = self::ConfirmUserRecharge($paras['out_trade_no'],$paras['price']);
        if( $res['state'] == 200 ){
            return ['state' => 200,'msg' => true];
        }else{
            self::userRechargeError($paras['out_trade_no']);
            return ['state'=>404,'msg'=>false];
        }
    }
    private static function sdwechatpayNotify($payline, $paras) //微信扫码回调
    {
        $res = self::ConfirmUserRecharge($paras['out_trade_no'],$paras['price']);
        if( $res['state'] == 200 ){
            return ['state' => 200,'msg' => true];
        }else{
            self::userRechargeError($paras['out_trade_no']);
            return ['state'=>404,'msg'=>false];
        }
    }


    private static function sdpayOrderQuery($orderid, $payline, $paras)
    {
        global $db;
        $Trade_No = $orderid;
    }

    #endregion

    #region 诚易通支付
    public static function cytunionfastpay($paras,$payline)//前台快捷
    {
        return self::cytGetParamsToUrl($paras,$payline,'UNIONFASTPAY');
    }
    public static function cytalipaypay($paras,$payline)//前台快捷支付宝PC扫码
    {
        return self::cytGetParamsToUrl($paras,$payline,'UFALIPAY');
    }
    public static function cytwechatpay($paras,$payline)//前台快捷微信PC扫码
    {
        return self::cytGetParamsToUrl($paras,$payline,'UFWECHAT');
    }
    private static function cytGetParamsToUrl($paras,$payline,$istype)
    {
        switch ( $istype ) {
            case 'UNIONFASTPAY':
                $paytype = 'cytunionfastpay';
                break;
            case 'UFALIPAY':
                $paytype = 'cytalipaypay';
                break;
            case 'UFWECHAT':
                $paytype = 'cytwechatpay';
                break;
            default:
                $paytype = '';
                break;
        }

        $data = [
            'p1_mchtid' => $payline['memcode'],
            'p2_paytype' => $istype,
            'p3_paymoney'   => $paras['paycoin'],
            'p4_orderno'    => $paras['rechargeid'],
            'p5_callbackurl'=> $paras['notify_url'],
            'p6_notifyurl'  => $paras['synchro_url'],
            'p7_version'    => 'v2.9',
            'p8_signtype'   => 2,
            'p9_attach'     => '',
            'p10_appname'   => '',
            'p11_isshow'    => 0, //写死的值
            'p12_orderip'   => long2ip($paras['remoteip']),
            'p13_memberid'  => $paras['uid'],
        ];
        $sign_str = "";
        foreach($data as $x=>$x_value)
        {
            if($sign_str==""){
                $sign_str = $sign_str.$x .'='. $x_value;
            }else{
                $sign_str = $sign_str.'&'.$x .'='. $x_value;
            }

        }
        $request = [];
        //生成签名
        $sign = md5($sign_str.$payline['md5key']);
        $data["sign"] = $sign;
        //转为json字符串
        $dataJson = json_encode($data);
        //获取公钥
        $publicStr = "-----BEGIN PUBLIC KEY-----\n".$payline['pubkey']."\n-----END PUBLIC KEY-----";
        //RSA公钥加密
        $key = openssl_get_publickey($publicStr);
        $original_arr = str_split($dataJson,117);
        foreach($original_arr as $o) {
            $sub_enc = null;
            openssl_public_encrypt($o,$sub_enc,$key);
            $original_enc_arr[] = $sub_enc;
        }

        openssl_free_key($key);
        $reqdata = base64_encode(implode('',$original_enc_arr));

        $request["mchtid"] = $data["p1_mchtid"];
        $request["reqdata"] = $reqdata;

        if( $istype == 'UNIONFASTPAY'){
            return [
                'state' => 200,
                'datas' => $request,
                'paytype' => $paytype,
            ];
        }else{
            $res = self::http('http://gate.chengyitpay.com/api/pay/v2',$request,true);

            if( $res['rspCode'] == 1 ){
                return [
                    'state' => 200,
                    'datas' => $res,
                    'paytype' => $paytype,
                ];
            }else{
                if( $res['rspCode'] == 10014 ){
                    self::userRechargeError($data['p4_orderno']);
                    return [
                        'state' => 404,
                        'msgid' => 10118,
                        'msg'   => $res['rspMsg'],
                    ];
                }else{
                    self::userRechargeError($data['p4_orderno']);
                    return [
                        'state' => 404,
                        'msgid' => $res['rspCode'],
                        'msg'   => $res['rspMsg'],
                    ];
                }

            }


        }
    }
    private static function cytunionfastpayNotify($payline, $paras)
    {
        self::cytpayNotify($payline, $paras);
    }
    private static function cytalipaypayNotify($payline, $paras)
    {
        self::cytpayNotify($payline, $paras);
    }
    private static function cytwechatpayNotify($payline, $paras)
    {
        self::cytpayNotify($payline, $paras);
    }
    private static function cytpayNotify($payline, $paras)
    {

        $resultJson = json_encode($paras);
        //待解密字符串
        $reqdata = $paras["reqdata"];
        //判断字符串是否需要 urldecode解码
        if(strpos($reqdata,"%")){
            $reqdata =  urldecode($reqdata);
        }
        //获取私钥
        $private_key = $payline['rsaprikey'];

        $pr_key = openssl_pkey_get_private($private_key);
        if ($pr_key == false){
            echo "打开密钥出错";
            die;
        }
        $data = base64_decode($reqdata);
        $crypto = '';
        //分段解密
        foreach (str_split($data, 128) as $chunk) {
            openssl_private_decrypt($chunk, $decryptData, $pr_key);
            $crypto .= $decryptData;
        }

        //解密
        $dataJson = $crypto;
        if($dataJson){
            //将json字符串转为数组
            $arr = json_decode($dataJson,true);
            //去除不需要参入验签的字段
            unset($arr["sysnumber"]);
            unset($arr["attach"]);
            $md5 = $payline['md5key'];

            $signStr = $arr['sign'];
            $sign_array = array();
            foreach ($arr as $k => $v) {
                if ($k !== 'sign'){
                    $sign_array[$k] = $v;
                }
            }

            $sign_str = "";
            foreach($sign_array as $x=>$x_value)
            {
                if($sign_str==""){
                    $sign_str = $sign_str.$x .'='. $x_value;
                }else{
                    $sign_str = $sign_str.'&'.$x .'='. $x_value;
                }
            }

            $sign  = md5($sign_str.$md5);
            if($signStr != $sign){

                self::userRechargeError($paras['ordernumber']);
                return ['state' => 404,'msg' => '验签失败'];
            }
            if($arr["orderstatus"] == 1){
                self::ConfirmUserRecharge($paras['ordernumber'],$paras['paymoney']);
                return ['state'=>200,'msg'=>'ok'];
            }else{
                self::userRechargeError($paras['ordernumber']);
                return ['state'=>200,'msg'=>'订单失败'];
            }
        }else{
            self::userRechargeError($paras['ordernumber']);
            var_dump('解密失败');
            return ['state' => 404,'msg' => '解密失败'];
        }
    }
    public static function cytunionfastpayOrderQuery($orderid, $payline, $paras)
    {
        self::cytOrderQuery($orderid, $payline, $paras);
    }
    public static function cytalipaypayOrderQuery($orderid, $payline, $paras)
    {
        self::cytOrderQuery($orderid, $payline, $paras);
    }
    public static function cytwechatpayOrderQuery($orderid, $payline, $paras)
    {
        self::cytOrderQuery($orderid, $payline, $paras);
    }
    public static function cytOrderQuery($orderid, $payline, $paras)
    {
        if( !isset($payline['memcode']) || !$payline['md5key'] ){
            return false;
        }
        $data = [
            'p1_mchtid'     => $payline['memcode'],
            'p2_signtype'   => 2,
            'p3_orderno'    => $orderid,
            'p4_version'    => 'v2.9',

        ];
        $sign_str = "";
        foreach($data as $x=>$x_value)
        {
            if($sign_str==""){
                $sign_str = $sign_str.$x .'='. $x_value;
            }else{
                $sign_str = $sign_str.'&'.$x .'='. $x_value;
            }

        }
        $request = [];
        //生成签名
        $sign = md5($sign_str.$payline['md5key']);
        $data["sign"] = $sign;
        //转为json字符串
        $dataJson = json_encode($data);
        //获取公钥
        $publicStr = "-----BEGIN PUBLIC KEY-----\n".$payline['pubkey']."\n-----END PUBLIC KEY-----";
        //RSA公钥加密
        $key = openssl_get_publickey($publicStr);
        $original_arr = str_split($dataJson,117);
        foreach($original_arr as $o) {
            $sub_enc = null;
            openssl_public_encrypt($o,$sub_enc,$key);
            $original_enc_arr[] = $sub_enc;
        }

        $reqdata = base64_encode(implode('',$original_enc_arr));

        $request["mchtid"] = $data["p1_mchtid"];
        $request["reqdata"] = $reqdata;
        $res = self::post('https://gatecx.chengyitpay.com/api/pay/query',$request);
        $res = json_decode($res,true);
        if( $res['rspCode'] == 1 && $res['data']['r5_orderstate'] == 1 ){
            self::ConfirmUserRecharge($res['data']['r3_orderno'],$res['data']['r4_amount']);
        }
    }
    #endregion

    # region 豆瓣支付
    public static function dbalipaypay($paras,$payline) //支付宝支付
    {
        return self::dbGetParamsToUrl($paras,$payline,'946');
    }
    private static function dbGetParamsToUrl($paras,$payline,$istype)
    {
        $pay_memberid   = $payline['memcode']; //商户号
        $pay_orderid    = $paras['rechargeid'];
        $pay_applydate  = date('Y-m-d H:i:s',$paras['nowtime']);
        $pay_bankcode   = $istype;
        $pay_notifyurl  = $paras['notify_url'];
        $pay_callbackurl= $paras['synchro_url'];
        $pay_amount     = $paras['amount'];
        $pay_productname= $paras['subject'];
        $pay_productdesc= $paras['body'];
        $key = $payline['md5key'];

        $sign_str = '';
        $sign_str = $sign_str . 'pay_amount=' . $pay_amount;
        $sign_str = $sign_str . '&pay_applydate=' . $pay_applydate;
        $sign_str = $sign_str . '&pay_bankcode=' . $pay_bankcode;
        $sign_str = $sign_str . '&pay_callbackurl=' . $pay_callbackurl;
        $sign_str = $sign_str . '&pay_memberid=' . $pay_memberid;
        $sign_str = $sign_str . '&pay_notifyurl=' . $pay_notifyurl;
        $sign_str = $sign_str . '&pay_orderid=' . $pay_orderid;
        $sign_str = $sign_str . '&key=' . $key;
        $sign = strtoupper(md5($sign_str));

        $data = [
            'pay_memberid'  => $pay_memberid,
            'pay_orderid'   => $pay_orderid,
            'pay_applydate' => $pay_applydate,
            'pay_bankcode'  => $pay_bankcode,
            'pay_notifyurl' => $pay_notifyurl,
            'pay_callbackurl' => $pay_callbackurl,
            'pay_amount'    => $pay_amount,
            'pay_md5sign'   => $sign,
            'pay_productname' => $pay_productname,
            'pay_productdesc' => $pay_productdesc
        ];
        var_dump($data);
        $res = self::http('http://doubanpro.com/user_Login_index.html',$data);
        var_dump($res);

    }
    private static function dbalipaypayNotify($payline, $paras)
    {
        if( $paras['returncode'] == 00 ){
            self::ConfirmUserRecharge($paras['orderid'],$payline['amount']);
            return ['state'=>200,'msg'=>'ok'];
        }else{
            self::userRechargeError($paras['orderid']);
            return ['state'=>200,'msg'=>'fail'];
        }
    }
    private static function dbalipaypayOrderQuery($orderid, $payline, $paras)
    {

    }

    # endregion

    # region 老马支付
    public static function lmalipaypay($paras,$payline) //支付宝支付
    {
        return self::lmGetParamsToUrl($paras,$payline,1);
    }
    public static function lmunionpay($paras,$payline) //云闪付
    {
        return self::lmGetParamsToUrl($paras,$payline,2);
    }
    public static function lmwechatpay($paras,$payline) //微信支付
    {
        return self::lmGetParamsToUrl($paras,$payline,4);
    }
    private static function lmGetParamsToUrl($paras,$payline,$istype)
    {
        $account = $payline['memcode'];
        $orderAmount = $paras['amount']*100;
        $callBackAddress = $paras['notify_url'];
        $jumpPage = $paras['synchro_url'];
        $payType = $istype;
        $orderNo = $paras['rechargeid'];
        $data = [
            'account'       => $account,
            'orderAmount'   => $orderAmount,
            'callBackAddress' => $callBackAddress,
            'jumpPage'      => $jumpPage,
            'payType'       => $payType,
            'orderNo'       => substr($orderNo,0,14)
        ];
        ksort($data);
        $sign = '';
        foreach ($data as $k => $v) {
            if ($v != '') {
                $sign .= $k . '=' . $v . '&';
            }
        }
        $sign = strtoupper(md5($sign . 'key=' . $payline['md5key']));
        $data['sign'] = $sign;
        $uri = '';
        foreach ( $data as $k => $v ){
            if ($v != '') {
                $uri .= $k . '=' . $v;
            }
        }
        $res = self::get('http://laoma66.com/payApi/getCollectUrl',$data);
        return true;
    }
    private static function lmalipaypayOrderQuery()
    {

    }
    # endregion

    #region 银信宝支付
    public static function yxbh5alipaypay($paras,$payline) //支付宝h5
    {
        return self::yxbGetParamsToUrl($paras,$payline,'20000203');
    }
    public static function yxbalipaypay($paras,$payline) //支付宝扫码
    {
        return self::yxbGetParamsToUrl($paras,$payline,'20000303');
    }
    public static function yxbh5wechatpay($paras,$payline) //微信h5
    {
        return self::yxbGetParamsToUrl($paras,$payline,'10000203');
    }
    public static function yxbwechatpay($paras,$payline) //微信扫码
    {
        return self::yxbGetParamsToUrl($paras,$payline,'10000103');
    }
    private static function yxbGetParamsToUrl($paras,$payline,$istype)
    {
        switch ( $istype ){
            case '20000203':
                $paytype = 'yxbh5alipaypay';
                break;
            case '20000303':
                $paytype = 'yxbalipaypay';
                break;
            case '10000203':
                $paytype = 'yxbh5wechatpay';
                break;
            case '10000103':
                $paytype = 'yxbwechatpay';
                break;
            default:
                $paytype = '';
                break;
        }
        $payKey = $payline['memcode'];
        $orderPrice = $paras['amount'];
        $outTradeNo = $paras['rechargeid'];
        $productType = $istype;
        $orderTime = date('YmdHis',$paras['nowtime']);
        $productName = $paras['subject'];
        $orderIp = long2ip($paras['remoteip']);
        $returnUrl = $paras['synchro_url'];
        $notifyUrl = $paras['notify_url'];

        $data = [
            'payKey'    => $payKey,
            'orderPrice'=> $orderPrice,
            'outTradeNo'=> $outTradeNo,
            'productType' => $productType,
            'orderTime' => $orderTime,
            'productName' => $productName,
            'orderIp'   => $orderIp,
            'returnUrl' => $returnUrl,
            'notifyUrl' => $notifyUrl
        ];
        ksort($data);
        $sign_str = '';
        foreach ($data as $k => $v) {
            if ($v != '') {
                $sign_str .= $k . '=' . $v . '&';
            }
        }
        $sign_str = $sign_str . 'paySecret=' . $payline['md5key'];
        $sign = strtoupper(md5($sign_str));
        $data['sign'] = $sign;
        $res = self::post('http://client.1jidai.com/cnpPay/initPay',$data);
        $res = json_decode($res,true);
        if( $res['resultCode'] == 0000 ){
            return [
                'state' => 200,
                'datas' => $res,
                'paytype' => $paytype,
            ];
        }else{
            self::userRechargeError($outTradeNo);
            return [
                'state' => 404,
                'msgid' => 10078,
                'msg'   => '支付失败',
            ];
        }

    }
    private static function yxbh5alipaypayNotify($payline, $paras)
    {
        if( $paras['tradeStatus'] === 'SUCCESS'){
            self::ConfirmUserRecharge($paras['outTradeNo'],$paras['orderPrice']);
            return ['state' => 200,'msg' => 'SUCCESS'];
        }elseif( $paras['tradeStatus'] == 'FAILED' ){
            self::userRechargeError($paras['outTradeNo']);
            return ['state'=>404,'msg'=>'FAILED'];
        }else{
            return ['state'=>404,'msg'=>$paras['tradeStatus']];
        }
    }
    private static function yxbalipaypayNotify($payline, $paras)
    {
        if( $paras['tradeStatus'] === 'SUCCESS'){
            self::ConfirmUserRecharge($paras['outTradeNo'],$paras['orderPrice']);
            return ['state' => 200,'msg' => 'SUCCESS'];
        }elseif( $paras['tradeStatus'] == 'FAILED' ){
            self::userRechargeError($paras['outTradeNo']);
            return ['state'=>404,'msg'=>'FAILED'];
        }else{
            return ['state'=>404,'msg'=>$paras['tradeStatus']];
        }
    }
    private static function yxbh5wechatpayNotify($payline, $paras)
    {
        if( $paras['tradeStatus'] === 'SUCCESS'){
            self::ConfirmUserRecharge($paras['outTradeNo'],$paras['orderPrice']);
            return ['state' => 200,'msg' => 'SUCCESS'];
        }elseif( $paras['tradeStatus'] == 'FAILED' ){
            self::userRechargeError($paras['outTradeNo']);
            return ['state'=>404,'msg'=>'FAILED'];
        }else{
            return ['state'=>404,'msg'=>$paras['tradeStatus']];
        }
    }
    private static function yxbwechatpayNotify($payline, $paras)
    {
        if( $paras['tradeStatus'] === 'SUCCESS'){
            self::ConfirmUserRecharge($paras['outTradeNo'],$paras['orderPrice']);
            return ['state' => 200,'msg' => 'SUCCESS'];
        }elseif( $paras['tradeStatus'] == 'FAILED' ){
            self::userRechargeError($paras['outTradeNo']);
            return ['state'=>404,'msg'=>'FAILED'];
        }else{
            return ['state'=>404,'msg'=>$paras['tradeStatus']];
        }
    }
    private static function yxbh5alipaypayOrderQuery()
    {

    }
    private static function yxbalipaypayOrderQuery()
    {

    }
    private static function yxbh5wechatpayOrderQuery()
    {

    }
    private static function yxbwechatpayOrderQuery()
    {

    }

    #endregion

    #region 鼎盛支付
    public static function dsh5alipaypay($paras,$payline) //支付宝h5
    {
        return self::dsGetParamsToUrl($paras,$payline,'20000203');
    }
    public static function dsalipaypay($paras,$payline) //支付宝扫码
    {
        return self::dsGetParamsToUrl($paras,$payline,'20000303');
    }
    public static function dsh5wechatpay($paras,$payline) //微信h5
    {
        return self::dsGetParamsToUrl($paras,$payline,'10000203');
    }
    public static function dswechatpay($paras,$payline) //微信扫码
    {
        return self::dsGetParamsToUrl($paras,$payline,'10000103');
    }
    private static function dsGetParamsToUrl($paras,$payline,$istype)
    {
        switch ( $istype ){
            case '20000203':
                $paytype = 'dsh5alipaypay';
                break;
            case '20000303':
                $paytype = 'dsalipaypay';
                break;
            case '10000203':
                $paytype = 'ds5wechatpay';
                break;
            case '10000103':
                $paytype = 'dswechatpay';
                break;
            default:
                $paytype = '';
                break;
        }
        $payKey = $payline['memcode'];
        $orderPrice = $paras['amount'];
        $outTradeNo = $paras['rechargeid'];
        $productType = $istype;
        $orderTime = date('YmdHis',$paras['nowtime']);
        $productName = $paras['subject'];
        $orderIp = long2ip($paras['remoteip']);
        $returnUrl = $paras['synchro_url'];
        $notifyUrl = $paras['notify_url'];

        $data = [
            'payKey'    => $payKey,
            'orderPrice'=> $orderPrice,
            'outTradeNo'=> $outTradeNo,
            'productType' => $productType,
            'orderTime' => $orderTime,
            'productName' => $productName,
            'orderIp'   => $orderIp,
            'returnUrl' => $returnUrl,
            'notifyUrl' => $notifyUrl
        ];
        ksort($data);
        $sign_str = '';
        foreach ($data as $k => $v) {
            if ($v != '') {
                $sign_str .= $k . '=' . $v . '&';
            }
        }
        $sign_str = $sign_str . 'paySecret=' . $payline['md5key'];
        $sign = strtoupper(md5($sign_str));
        $data['sign'] = $sign;
        $res = self::post('http://gataway.feaf-inc.com/cnpPay/initPay',$data);
        $res = json_decode($res,true);
        if( $res['resultCode'] == 0000 ){
            return [
                'state' => 200,
                'datas' => $res,
                'paytype' => $paytype,
            ];
        }else{
            self::userRechargeError($outTradeNo);
            return [
                'state' => 404,
                'msgid' => 10078,
                'msg'   => '支付失败',
            ];
        }

    }
    private static function dsh5alipaypayNotify($payline, $paras)
    {
        if( $paras['tradeStatus'] === 'SUCCESS'){
            self::ConfirmUserRecharge($paras['outTradeNo'],$paras['orderPrice']);
            return ['state' => 200,'msg' => 'SUCCESS'];
        }elseif( $paras['tradeStatus'] == 'FAILED' ){
            self::userRechargeError($paras['outTradeNo']);
            return ['state'=>404,'msg'=>'FAILED'];
        }else{
            return ['state'=>404,'msg'=>$paras['tradeStatus']];
        }
    }
    private static function dsalipaypayNotify($payline, $paras)
    {
        if( $paras['tradeStatus'] === 'SUCCESS'){
            self::ConfirmUserRecharge($paras['outTradeNo'],$paras['orderPrice']);
            return ['state' => 200,'msg' => 'SUCCESS'];
        }elseif( $paras['tradeStatus'] == 'FAILED' ){
            self::userRechargeError($paras['outTradeNo']);
            return ['state'=>404,'msg'=>'FAILED'];
        }else{
            return ['state'=>404,'msg'=>$paras['tradeStatus']];
        }
    }
    private static function dsh5wechatpayNotify($payline, $paras)
    {
        if( $paras['tradeStatus'] === 'SUCCESS'){
            self::ConfirmUserRecharge($paras['outTradeNo'],$paras['orderPrice']);
            return ['state' => 200,'msg' => 'SUCCESS'];
        }elseif( $paras['tradeStatus'] == 'FAILED' ){
            self::userRechargeError($paras['outTradeNo']);
            return ['state'=>404,'msg'=>'FAILED'];
        }else{
            return ['state'=>404,'msg'=>$paras['tradeStatus']];
        }
    }
    private static function dswechatpayNotify($payline, $paras)
    {
        if( $paras['tradeStatus'] === 'SUCCESS'){
            self::ConfirmUserRecharge($paras['outTradeNo'],$paras['orderPrice']);
            return ['state' => 200,'msg' => 'SUCCESS'];
        }elseif( $paras['tradeStatus'] == 'FAILED' ){
            self::userRechargeError($paras['outTradeNo']);
            return ['state'=>404,'msg'=>'FAILED'];
        }else{
            return ['state'=>404,'msg'=>$paras['tradeStatus']];
        }
    }
    private static function dsh5alipaypayOrderQuery()
    {

    }
    private static function dsalipaypayOrderQuery()
    {

    }
    private static function dsh5wechatpayOrderQuery()
    {

    }
    private static function dswechatpayOrderQuery()
    {

    }

    #endregion

    # region 黑猫支付
    public static function hmwechatpay($paras,$payline){
        return self::hmGetParamsToUrl($paras,$payline,'WECHANT');
    }
    public static function hmalipaypay($paras,$payline){
        return self::hmGetParamsToUrl($paras,$payline,'ALIPAY');
    }
    public static function hmunionpay($paras,$payline){
        return self::hmGetParamsToUrl($paras,$payline,'QUICKPAY');
    }
    public static function hmwebpay($paras,$payline){
        return self::hmGetParamsToUrl($paras,$payline,'WEBPAY');
    }
    private static function hmGetParamsToUrl($paras,$payline,$istype)
    {
        switch ( $istype ){
            case 'WECHANT':
                $paytype = 'hmwechatpay';
                break;
            case 'ALIPAY':
                $paytype = 'hmalipaypay';
                break;
            case 'QUICKPAY':
                $paytype = 'hmunionpay';
                break;
            case 'WEBPAY':
                $paytype = 'hmwebpay';
                break;
            default:
                $paytype = '';
                break;
        }
        $mid_no = $payline['memcode'];
        $order_no = $paras['rechargeid'];
        $type = $istype;
        $order_amount = $paras['amount'] * 100;
        $remark = $paras['uid'];
        $unified_order_time = date('YmdHis',$paras['nowtime']);
        $notice_url = $paras['notify_url'];
        $front_url = $paras['synchro_url'];
        $data = [
            'mid_no'    => $mid_no,
            'order_no'  => $order_no,
            'type'      => $type,
            'order_amount' => $order_amount,
            'remark'    => $remark,
            'unified_order_time' => $unified_order_time,
            'notice_url'=> $notice_url,
            'front_url' => $front_url,
        ];
        ksort($data);
        $transStr="";
        $flag=1;
        foreach($data as $v=>$a)
        {
            if(sizeof($data)==$flag){
                $transStr= $transStr.$v."=".$a;
            }else{
                $transStr= $transStr.$v."=".$a."&";
            }
            $flag++;
        }
        $sign = md5($transStr.$payline['md5key'],false);
        $data['sign'] = $sign;
        //$res = self::http('http://47.105.161.82/pay/gateway/unifiedorder',$data);
        return [
            'state' => 200,
            'datas' => $data,
            'paytype' => $paytype,
        ];
    }
    private static function hmwechatpayNotify($payline, $paras)
    {
        if( $paras['resp_code'] == 0 && $paras['status'] == 0 ){
            self::ConfirmUserRecharge($paras['order_no'],$paras['order_amount'] / 100);
            return ['state' => 200,'msg' => 'SUCCESS'];
        }else{
            self::userRechargeError($paras['order_no']);
            return ['state'=>404,'msg'=>'ERROR'];
        }
    }
    private static function hmalipaypayNotify($payline, $paras)
    {
        if( $paras['resp_code'] == 0 && $paras['status'] == 0 ){
            self::ConfirmUserRecharge($paras['order_no'],$paras['order_amount'] / 100);
            return ['state' => 200,'msg' => 'SUCCESS'];
        }else{
            self::userRechargeError($paras['order_no']);
            return ['state'=>404,'msg'=>'ERROR'];
        }
    }
    private static function hmunionpayNotify($payline, $paras)
    {
        if( $paras['resp_code'] == 0 && $paras['status'] == 0 ){
            self::ConfirmUserRecharge($paras['order_no'],$paras['order_amount'] / 100);
            return ['state' => 200,'msg' => 'SUCCESS'];
        }else{
            self::userRechargeError($paras['order_no']);
            return ['state'=>404,'msg'=>'ERROR'];
        }
    }
    private static function hmwebpayNotify($payline, $paras)
    {
        if( $paras['resp_code'] == 0 && $paras['status'] == 0 ){
            self::ConfirmUserRecharge($paras['order_no'],$paras['order_amount'] / 100);
            return ['state' => 200,'msg' => 'SUCCESS'];
        }else{
            self::userRechargeError($paras['order_no']);
            return ['state'=>404,'msg'=>'ERROR'];
        }
    }


    private static function hmwechatpayOrderQuery()
    {

    }
    private static function hmalipaypayOrderQuery()
    {

    }
    private static function hmunionpayOrderQuery()
    {

    }
    private static function hmwebpayOrderQuery()
    {

    }

    # endregion

    # region 用户充值失败
    public static function userRechargeError($orderid)
    {
        global $db;
        $db_prefix = \Config\Sys::$dbprefix;
        $para = [
            'state'=>2,
            'info'=>'',
            'actionuid' => $orderid,
            'rechargetime' => time(),
            'rechargeamount'=>0,
        ];
        $sql = "SELECT r.`id`,r.`uid`,r.`amount`,u.`agentlevel`,u.`userlevel`,l.`give`,u.`parentid`,u.`usertype`,r.`state` from `{$db_prefix}users_recharge` r,`{$db_prefix}users` u,`{$db_prefix}rechargeline` l WHERE u.`uid`=r.`uid` AND l.`id`=r.`lineid` AND r.`rechargeid`='{$orderid}' LIMIT 1";
        $recharge = $db->row($sql);
        if( $recharge ){
            $db->update($db_prefix.'users_recharge')->cols(array(
                'state' => 2,
                'rechargetime' => time(),
                'rechargeamount' => 0,
                'info' => '充值失败',
            ))->where('id='.$recharge['id'])->query();
        }else{
            $db->delete($db_prefix.'users_recharge')->where("rechargeid='{$orderid}'")->query();
        }


    }
    # endregion

    # region 支付测试线路
    public static function xinyihepay($paras, $payline)
    {
        // 获取支付金额
        $paycoin = floatval($paras['paycoin']);
        $paycoin = number_format($paycoin,2,".","");

        $apiUrl = "http://www.xinyihe-techinfo.com/netpos/app/create/order";

        $postData = array(
            'appId' => $payline['memcode'], // --
            'notifyUrl' => $paras['notify_url'],
            'payMethod' => '1', // 1->支付宝
            'returnUrl' => $paras['synchro_url'],
            'subject' => '测试支付',
            'totalAmount' => $paycoin,
            'tradeNo' => $paras['rechargeid'], // --
        );

        $signStr = '';
        foreach ($postData as $key=>$val)
        {
            $signStr .= $key.'='.$val.'&';
        }

        $signStr .= 'key=' . $payline['md5key'];


        $sign = md5($signStr);

        $postData['sign'] = strtoupper($sign);

        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$apiUrl); // 抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); // 设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); // post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        $data = curl_exec($ch);
        curl_close($ch);

        $arr = json_decode($data,true);

        $result = '';

        foreach ($arr['biz_content'][0] as $key=>$val)
        {
            $result .= $key.'='.$val.'&';
        }
        $result = substr($result,0,(strlen($result)-1));

        return array(
            'state' => 200,
            'datas' => $result,
            'request' => $arr,
            'paytype' => 'alipay',
        );
    }
    # endregion
    public static function post($url, $params = [], $options = [])
    {
        $req = self::sendRequest($url, $params, 'POST', $options);
        return $req['ret'] ? $req['msg'] : '';
    }
    public static function sendRequest($url, $params = [], $method = 'POST', $options = [])
    {
        $method = strtoupper($method);
        $protocol = substr($url, 0, 5);
        $query_string = is_array($params) ? http_build_query($params) : $params;

        $ch = curl_init();
        $defaults = [];
        if ('GET' == $method) {
            $geturl = $query_string ? $url . (stripos($url, "?") !== false ? "&" : "?") . $query_string : $url;
            $defaults[CURLOPT_URL] = $geturl;
        } else {
            $defaults[CURLOPT_URL] = $url;
            if ($method == 'POST') {
                $defaults[CURLOPT_POST] = 1;
            } else {
                $defaults[CURLOPT_CUSTOMREQUEST] = $method;
            }
            $defaults[CURLOPT_POSTFIELDS] = $query_string;
        }

        $defaults[CURLOPT_HEADER] = false;
        $defaults[CURLOPT_USERAGENT] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.98 Safari/537.36";
        $defaults[CURLOPT_FOLLOWLOCATION] = true;
        $defaults[CURLOPT_RETURNTRANSFER] = true;
        $defaults[CURLOPT_CONNECTTIMEOUT] = 3;
        $defaults[CURLOPT_TIMEOUT] = 3;

        // disable 100-continue
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));


        if ('https' == $protocol) {
            $defaults[CURLOPT_SSL_VERIFYPEER] = false;
            $defaults[CURLOPT_SSL_VERIFYHOST] = false;
        }

        curl_setopt_array($ch, (array)$options + $defaults);

        $ret = curl_exec($ch);
        $err = curl_error($ch);

        if (false === $ret || !empty($err)) {
            $errno = curl_errno($ch);
            $info = curl_getinfo($ch);
            curl_close($ch);
            return [
                'ret'   => false,
                'errno' => $errno,
                'msg'   => $err,
                'info'  => $info,
            ];
        }
        curl_close($ch);
        return [
            'ret' => true,
            'msg' => $ret,
        ];
    }
    public static function get($url, $params = [], $options = [])
    {
        $req = self::sendRequest($url, $params, 'GET', $options);
        return $req['ret'] ? $req['msg'] : '';
    }

    public static function http($url, $data = NULL, $json = false)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            if($json && is_array($data)){
                $data = json_encode( $data );
            }
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            if($json){ //发送JSON数据
                curl_setopt($curl, CURLOPT_HEADER, 0);
                curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($data)));
            }
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return array(
                'errorno' => false,
                'errmsg' => $errorno
            );
        }
        curl_close($curl);
        return json_decode($res, true);
    }
}

#region 支付宝相关
class AlipayTradeQueryRequest
{
    /**
     * 统一收单线下交易查询
    修改路由策略到R
     **/
    private $bizContent;

    private $apiParas = array();
    private $terminalType;
    private $terminalInfo;
    private $prodCode;
    private $apiVersion="1.0";
    private $notifyUrl;
    private $returnUrl;
    private $needEncrypt=false;


    public function setBizContent($bizContent)
    {
        $this->bizContent = $bizContent;
        $this->apiParas["biz_content"] = $bizContent;
    }

    public function getBizContent()
    {
        return $this->bizContent;
    }

    public function getApiMethodName()
    {
        return "alipay.trade.query";
    }

    public function setNotifyUrl($notifyUrl)
    {
        $this->notifyUrl=$notifyUrl;
    }

    public function getNotifyUrl()
    {
        return $this->notifyUrl;
    }

    public function setReturnUrl($returnUrl)
    {
        $this->returnUrl=$returnUrl;
    }

    public function getReturnUrl()
    {
        return $this->returnUrl;
    }

    public function getApiParas()
    {
        return $this->apiParas;
    }

    public function getTerminalType()
    {
        return $this->terminalType;
    }

    public function setTerminalType($terminalType)
    {
        $this->terminalType = $terminalType;
    }

    public function getTerminalInfo()
    {
        return $this->terminalInfo;
    }

    public function setTerminalInfo($terminalInfo)
    {
        $this->terminalInfo = $terminalInfo;
    }

    public function getProdCode()
    {
        return $this->prodCode;
    }

    public function setProdCode($prodCode)
    {
        $this->prodCode = $prodCode;
    }

    public function setApiVersion($apiVersion)
    {
        $this->apiVersion=$apiVersion;
    }

    public function getApiVersion()
    {
        return $this->apiVersion;
    }

    public function setNeedEncrypt($needEncrypt)
    {

        $this->needEncrypt=$needEncrypt;

    }

    public function getNeedEncrypt()
    {
        return $this->needEncrypt;
    }

}
class SignData {

    public $signSourceData=null;


    public $sign=null;

}
# endregion 支付宝相关

